如何读取 Maven Web 应用程序的 webapp 文件夹中的目录
我正在 Maven Web 应用程序中工作。我需要读取 webapp 文件夹中的目录(例如:文件),如下所示,
Java.io.File file = new Java.io.File("path");
但我不知道如何在此处指定目录的路径。
I'm working in maven web application. I need to read a directory(For ex: Files) in my webapp folder as follows,
Java.io.File file = new Java.io.File("path");
But I don't know how to specify the path of the directory here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该提供本地路径地址。路径应该是相对地址,例如 Web 存档 (.war) 文件夹下的
/files/images
。要正确使用相对路径,我建议您将目标文件夹添加到 POM.xml 的资源定义中,请查看这些页面
http://www.mkyong.com/maven/如何更改 maven-resources-folder-location/
http://maven.apache.org/guides /introduction/introduction-to-the-standard-directory-layout.html
您可以使用以下内容轻松引用资源文件夹:
You shouldn't give local path addresses. Path should be a relative address, e.g.
/files/images
under your web archive (.war) folder.To use relative paths properly, I suggest you to add your target folder to the resources definiton of POM.xml, check out these pages
http://www.mkyong.com/maven/how-to-change-maven-resources-folder-location/
http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html
You can refer to resources folder easily with something like this:
当不确定相对路径如何工作时,最好这样做:
这将打印出类路径将在其中查找文件的路径。
假设:
/var/lib/tomcat6/webapps
my-webapp.war
您应该看到以下输出:
/var/lib/tomcat6/webapps/my-webapp/my/desired/directory
另一个指针:您已经提到您正在寻找
webapp
目录。我希望您知道此目录不会以*.war
结尾 - 它的内容会。When in doubt how relatives paths work, it's always best to do something like that:
This will print out the path in which classpath will look for the files.
Assuming:
/var/lib/tomcat6/webapps
my-webapp.war
You should see the following output:
/var/lib/tomcat6/webapps/my-webapp/my/desired/directory
Another pointer: you have mentioned that you are looking for
webapp
directory. I hope you know that this directory will not end up in*.war
- it's contents will.War 文件在部署到应用服务器时并不总是会扩展,因此文件系统中可能根本不存在相对路径。
最好的选择是使用类加载器中的 getResource,它将返回类路径(WEB-INF/lib 目录等)中的内容,或者使用 getResource() ServletContext 的方法在 Web 中查找内容应用程序本身。
War files are not always expanded when they are deployed to an app server, so it's possible that a relative path won't exist in a filesystem at all.
Best bets are to use getResource from the class loader, which will return things in the class path (the WEB-INF/lib directory, etc), or to use the getResource() method of ServletContext to find things in the web application itself.