Java getResource()无法读取jar中目录的内容
我刚刚谈到这个问题,jar中的主类无法读取文件夹的内容。 该类包含Java getResource()无法读取jar中目录的内容,java,jar,Java,Jar,我刚刚谈到这个问题,jar中的主类无法读取文件夹的内容。 该类包含 String path = "flowers/FL8-4_zpsd8919dcc.jpg"; try { File file = new File(TestResources.class.getClassLoader() .getResource(path).getPath()); System.out.println(fil
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内内容的读取机制有什么不同。
简单罐子的内容
您需要使用它来获得所期望的行为,例如,sp00m建议的/flowers/FL8-4zpsd8919dcc.jpg
。getResource()和getResourceAsStream()
都能够在jar中找到资源,它们使用相同的机制来定位资源
但是,当您从表示jar中的条目的URL
构造文件时,File.exists()
将返回false
File
不能用于检查jar/zip中是否存在文件
您只能使用本地文件系统(或附加到本地文件系统)上的File.exists
。能否尝试使用/flowers/FL8-4_zpsd8919dcc.jpg
?@sp00m仍然是空指针java.io.File
用于引用文件系统上的人工制品。单个JAR条目对文件系统不可见。是否有方法读取JAR中文件夹的文件并从中创建数组?假设我需要JAR中文件夹中的文件,那么如何在不使用JarFile
类的情况下获取该文件?您所说的“获取”是什么意思?将其内容读入字节数组?或者获取一个读取其内容的InputStream
?我需要jar中该文件夹的文件,并使用它创建和排列文件File
无法描述jar条目,您不应该使用它。相反,可以使用URL
s,您可以通过URL.openStream()
获取它们的内容,这对文件和jar/zip条目都很好。这里的场景是我需要文件夹中的文件,以便我可以将它们用于其他任务,我无法使用inputstream,因此无法使用任何方法来完成