[英]Problem loading resources from classpath
在一个本地的Tomcat运行的Web应用程序,我试图加载的文件夹/folder
它是在tomcat/webapps/myproject/WEB-INF/folder
要做到这一点:
InputStream realPath = getClass().getClassLoader().getResourceAsStream("/folder");
返回null
。 这段代码应该从classpath加载资源,如果我在我的文件夹所在的路径中没有错误的话。
无论如何,我将我的文件夹移动到不同的路径,例如tomcat/webapps/myproject/WEB-INF/classes/folder
或tomcat/webapps/myproject/WEB-INF/lib/folder
,结果相同。
我错过了什么? 提前致谢。
关于你的所有答案(谢谢),我用我尝试过的所有内容编辑我的问题,结果相同。
一种)
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
问题是/ WEB-INF不在WAR文件的CLASSPATH中。
/ WEB-INF / classes在CLASSPATH中; 所以/ WEB-INF / lib中的所有JAR也是如此。
如果将所需的文件放入/ WEB-INF / classes,WAR类加载器应该能够找到它。
你无法以这种方式读取目录。 它必须是一个文件。
更新:
无论如何,我将我的文件夹移动到不同的路径,例如tomcat / webapps / myproject / WEB-INF / classes /文件夹或tomcat / webapps / myproject / WEB-INF / lib /文件夹,结果相同。 我错过了什么?
是的,你错过了两件事:
如果您想要在webapp中使用文件夹的完整路径,以便可以对其使用文件操作,则可以使用以下方法。
注意:myfolder与我的webapp中的WEB-INF并行
String relativeWebPath = "/myfolder";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
现在打印出absoluteDiskPath
磁盘absoluteDiskPath
给了我
D:\apache-tomcat-6.0.20\webapps\mywebapp\myfolder
尝试列出该文件夹中的文件
File dir = new File(absoluteDiskPath);
String[] children = dir.list();
if (children != null)
{
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
System.out.println("filename no " + i + filename);
}
}
删除前导斜杠并尝试ie
InputStream realPath = getClass().getClassLoader().getResourceAsStream("folder");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.