我刚刚遇到这个问题,jar 内的主类无法读取文件夹的内容。
该类包含
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
try {
File file = new File(TestResources.class.getClassLoader()
.getResource(path).getPath());
System.out.println(file.exists());
} catch (Exception e) {
e.printStackTrace();
}
这里 sysout 返回false
.
但是当我尝试这样的事情时它会起作用
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
FileOutputStream out = null;
InputStream is = null;
try {
is = TestResources.class.getClassLoader().getResourceAsStream(path);
byte bytes[] = new byte[is.available()];
is.read(bytes);
out = new FileOutputStream("abc.jpg");
out.write(bytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
getResourceAsStream()
能够读取 jar 内文件夹的路径,但是getResource()
无法阅读它,
为什么会这样,这两种方法对jar内内容的读取机制有什么区别。
简单罐子的内容
Both getResource()
and getResourceAsStream()
能够在jar中找到资源,他们使用相同的机制来定位资源。
但是当你构造一个File
从一个URL
它表示罐子内的一个条目,File.exists()
将返回false
. File
不能用于检查 jar/zip 内的文件是否存在。
您只能使用File.exists
它们位于本地文件系统上(或附加到本地文件系统)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)