【发布时间】:2014-10-05 03:49:02
【问题描述】:
我刚遇到这个问题,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里面的内容的读取机制有什么区别。 简单jar的内容
【问题讨论】:
-
你能用
/flowers/FL8-4_zpsd8919dcc.jpg试试吗? -
@sp00m 仍然是空指针
-
java.io.File用于引用文件系统上的人工制品。单个 JAR 条目对文件系统不可见。 -
有没有办法读取 jar 内文件夹的文件并从中创建一个数组