我有一个propeties文件,其中包含jar中某个文件的路径
logo.cgp=images/cgp-logo.jpg此文件已存在:

我想在我的项目中加载这个文件,所以我这样做:
String property = p.getProperty("logo.cgp"); //This returns "images/cgp-logo.jpg"
File file = new File(getClass().getClassLoader().getResource(property).getFile());但是当我执行file.exists()时,我得到了false。当我选中file.getAbsolutePath()时,它会指向C:\\images\\cgp-logo.jpg
我做错了什么?
发布于 2016-02-10 17:59:10
jar中的文件只是,而不是常规文件。它是一种资源,可以由ClassLoader加载并作为流读取,但不能作为文件读取。
根据Javadoc的说法,getClass().getClassLoader().getResource(property)返回一个URL,而getFile()在一个URL上说:
获取此URL的文件名。返回的文件部分将与getPath()相同,加上getQuery()的值的连接(如果有的话)。如果没有查询部分,此方法和getPath()将返回相同的结果。
因此,对于jar资源,它与返回以下内容的getPath()相同:
此URL的路径部分,如果不存在,则为空字符串
因此,在这里,您将获得相对于类路径的/images/cgp-logo.jpg,它并不对应于文件系统上的实际文件。这也解释了file.getAbsolutePath()的返回值
访问资源的正确方法是:
InputStream istream = getClass().getClassLoader().getResourceAsStream(property)发布于 2016-02-10 17:39:43
您可以像这样使用JarFile类:
JarFile jar = new JarFile("foo.jar");
String file = "file.txt";
JarEntry entry = jar.getEntry(file);
InputStream input = jar.getInputStream(entry);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[input.available()];
for (int i = 0; i != -1; i = input.read(buffer)) {
output.write(buffer, 0, i);
}
} finally {
jar.close();
input.close();
output.close();
}https://stackoverflow.com/questions/35311304
复制相似问题