如何读取Maven应用程序的webapp文件夹中的目录
我正在 Maven Web 应用程序(Java)中工作。我需要读取 webapp 文件夹中的目录(例如:mydirectory),如下所示:
File file = new File("path of my directory");
我只是指定应用程序中的文件夹层次结构。
MyApplication->src->main->webapp->MyDirectory
但我将编写我的 Java 代码,如下所示,
MyApplication->src->main->java->com->mypackage->myfile.java
我需要从 myfile.java 中读取 webapp 中的目录“MyDirectory”。 as new File("目录的路径")
但我不知道如何在这里指定目录的路径。
I'm working in Maven web application (Java). I need to read a directory (for ex: mydirectory) in my webapp folder as follows:
File file = new File("path of my directory");
I just specify the hierarchy of folders in my application.
MyApplication->src->main->webapp->MyDirectory
But I'm going to write my Java code I the package as follows,
MyApplication->src->main->java->com->mypackage->myfile.java
From myfile.java I need to read the directory "MyDirectory" in webapp. As new File("path of the directory")
But I don't know how to specify the path of the directory here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
使用
getResource()
而不是getResourceAsStream()
Try
alternatively use
getResource()
instead ofgetResourceAsStream()
在运行时,不再有 Maven(感谢上帝!),并且不再有目录。您拥有的只是一个 war 文件,所有内容要么在 war 文件中,要么在应用程序外部的文件系统上。
使用
ServletContext .getResourceAsStream()
从 web 应用程序的上下文加载文件。At runtime, there is no maven anymore (thank God!), and there is no directory anymore. All you have is a war file, and everything is either in the war file, or somewhere outside of the app, on the file system.
Use
ServletContext.getResourceAsStream()
to load a file from the webapp's context.您没有提到您使用的技术/框架,但我想您至少使用了 Java servlet,因为您提到它是一个 Web 应用程序。所以你可以使用 ServletContext .getRealPath() 获取文件系统中的路径:
更新:
请注意该方法的 JavaDoc 说:
这意味着返回的路径:
\
,在 Linux/macOS 中使用/
等)。null
,例如,如果资源实际上位于内存中、JAR 文件中等等。因此:请仅在记住这些注意事项的情况下遵循我的答案,并更好地使用 ServletContext.getResourceAsStream()
You haven't mentioned what technology/framework you use, but I suppose you're using at least Java servlets, because you mentioned it's a web application. So you can use ServletContext.getRealPath() to get the path in the filesystem:
Update:
Please note that JavaDoc of the method says:
This means that the returned path:
\
, in Linux/macOS with/
, etc).null
, e.g. if the resource is virtually in memory, in a JAR file, or so.Therefore: please follow my answer only with those caveats in mind, and better follow the other answers using ServletContext.getResourceAsStream()
我无法访问 servlet 上下文,因为我需要从 webapp 文件夹读取数据的服务不知道当前的 servlet 上下文。
任何使用 Spring 的人都可以通过简单地实现 spring 框架提供的 ResourceLoaderAware 接口来访问 webapp 文件夹。
I couldn't access the servlet context since the service where i need to read data from the webapp folder is not aware of the current servlet context.
Anyone who is using Spring can never the less access the webapp folder by simply implementing the ResourceLoaderAware Interface provided by the spring framework.