从类路径加载资源时出现问题
在本地 tomcat 中运行的 Web 应用程序中,我尝试加载位于 tomcat/webapps/myproject/WEB-INF/folder
中的文件夹 /folder
要做到这一点:
InputStream realPath = getClass().getClassLoader().getResourceAsStream("/folder");
返回null
。这段代码应该从类路径加载资源,如果我的文件夹所在的路径没有错误的话。
无论如何,我将文件夹移动到不同的路径,例如 tomcat/webapps/myproject/WEB-INF/classes/folder 或 tomcat/webapps/myproject/WEB-INF/lib/folder< /code> 具有相同的结果。
我错过了什么吗?提前致谢。
关于您的所有答案(谢谢),我用我所尝试的一切编辑了我的问题,但结果相同。
A)
String realSource = getServletContext().getRealPath("/folder");
B)
InputStream realPath = getClass().getClassLoader().getResourceAsStream("/folder/fileInFolder");
C)
ServletContext servletContext = (ServletContext)context.getExternalContext().getContext();
String realSource = servletContext.getRealPath("/folder");
我必须说我的 folder
路径是 tomcat/webapps/myproject/WEB-INF/classes/folder
In a web application running in a local tomcat, I am trying to load a folder /folder
which is in tomcat/webapps/myproject/WEB-INF/folder
To do it:
InputStream realPath = getClass().getClassLoader().getResourceAsStream("/folder");
Which returns null
. This piece of code is supposed to load resources from classpath, which is if I am not wrong in the path where my folder is in.
Anyway, I moved my folder to different paths, such as tomcat/webapps/myproject/WEB-INF/classes/folder
or tomcat/webapps/myproject/WEB-INF/lib/folder
with the same result.
Did I miss something? Thanks in advance.
Regarding on all your answers (thanks), I edit my question with all I have tryed, with the same null result.
A)
String realSource = getServletContext().getRealPath("/folder");
B)
InputStream realPath = getClass().getClassLoader().getResourceAsStream("/folder/fileInFolder");
C)
ServletContext servletContext = (ServletContext)context.getExternalContext().getContext();
String realSource = servletContext.getRealPath("/folder");
I must say that my folder
path is tomcat/webapps/myproject/WEB-INF/classes/folder
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是 /WEB-INF 不在 WAR 文件的 CLASSPATH 中。
/WEB-INF/classes 位于 CLASSPATH 中; /WEB-INF/lib 中的所有 JAR 也是如此。
如果您将需要的文件放入 /WEB-INF/classes 中,WAR 类加载器应该能够找到它。
您无法以这种方式读取目录。它必须是一个文件。
更新:
是的,您错过了两件事:
The problem is that /WEB-INF is not in the CLASSPATH of a WAR file.
/WEB-INF/classes is in the CLASSPATH; so are all the JARs in /WEB-INF/lib.
If you put the file you need into /WEB-INF/classes the WAR class loader should be able to find it.
You cannot read a directory that way. It must be a file.
UPDATE:
Yes, you've missed two things:
如果您想要 Web 应用程序中文件夹的完整路径,以便可以对其使用文件操作,可以使用以下方法。
注意:myfolder 与我的 web 应用程序中的 WEB-INF 并行
现在打印
absoluteDiskPath
让我尝试通过以下方式列出该文件夹中的文件
If you want the full path of the folder within your webapp so that you can use File operations on it, here is a way to do it.
Note: myfolder is parallel to WEB-INF within my webapp
Now printing out
absoluteDiskPath
gives meTry listing files in that folder by
删除前导斜杠并尝试 ie
Remove the leading slash and try i.e.