如何获取WebContent文件夹中文件的真实路径?

11

我需要获取WebContent目录下的文件的真实路径,以便我使用的框架可以访问该文件。它只使用字符串文件作为属性,因此我需要获取WebContent目录中此文件的真实路径。

我使用Spring框架,因此解决方案应该可以在Spring中实现。

9个回答

13

getServletContext().getRealPath("") - 如果内容来自.war文件,这种方法将不起作用。 getServletContext() 将为空。

在这种情况下,我们可以使用另一种方法来获取真实路径。这是获取到属性文件路径的示例 C:/Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties:

// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");

// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");

if (decoded.startsWith("/")) {
    // path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
    decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");

13
如果您需要在servlet中实现此功能,请使用getServletContext().getRealPath("/filepathInContext")

4
请让控制器实现ServlexContextAware接口。 - OrangeDog
1
OrangeDog的评论非常正确。只是一个小小的更正,应该是ServletContextAware(而不是Servlex...)。 - Felby

2

您需要告诉Java将路径从您的电脑更改为您的Java项目,因此如果您使用Spring,请使用:

@Autowired
ServletContext c;

String UPLOAD_FOLDEdR=c.getRealPath("/images"); 

但如果您使用Servlet,只需使用
String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");  

因此,路径将为/webapp/images/ :)

0
将请求作为参数包含在其中。当Spring调用映射的方法时,它将传递请求对象。
@RequestMapping .....
public String myMethod(HttpServletRequest request) {
   String realPath = request.getRealPath("/somefile.txt");
   ...

0

这种方法使用资源加载器获取应用程序中文件的绝对路径,然后向上移动几个文件夹到应用程序的根文件夹。无需servlet上下文!如果您的WEB-INF文件夹中有“web.xml”,则应该可以正常工作。请注意,您可能希望仅将此用于开发,因为通常最好将此类型的配置存储在应用程序外部。

public String getAppPath()
{
    java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
    String filePath = r.getFile();
    String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();

    if (! filePath.contains("WEB-INF"))
    {
        // Assume we need to add the "WebContent" folder if using Jetty.
        result = FilenameUtils.concat(result, "WebContent");
    }

    return result;
}

0
在这种情况下,我倾向于提取我需要的内容作为资源(MyClass.getClass().getResourceAsStream()),将其写入临时位置并使用此文件进行其他调用。
这样,我就不必担心仅包含在jar中或根据我当前使用的Web容器位于某个位置的内容。

@tangens - 我认为他不想从webapps类加载器中读取资源;例如,在WAR中的JAR文件中的文件。他只是想获取Web容器内文件的路径名。 - Stephen C

0

0

我的解决方案是: ..../webapps/mydir/ (..../webapps/ROOT/../mydir/)

String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
            Files.createDirectories(Paths.get(dir));

-1

如果您想在开发和生产环境中使用arff.txt,可以尝试使用这个方法。

  String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");

虽然这段代码片段可能是解决方案,但包括解释真的有助于提高您的帖子质量。请记住,您正在回答未来读者的问题,而这些人可能不知道您的代码建议原因。 - yivi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接