我正在尝试获取一个资源的路径,但我没有运气。
这是有效的(在IDE和JAR中),但是通过这种方式,我不能获得文件的路径,只能获得文件内容:
ClassLoader classLoader = getClass().getClassLoader();
PrintInputStream(classLoader.getResourceAsStream("config/netclient.p"));
如果我这样做:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("config/netclient.p").getFile());
结果是:java.io.FileNotFoundException: file:/path/to/jarfile/bot.jar!/config/netclient.p (No such file or directory)
有没有办法获得资源文件的路径?
发布于 2009-06-02 20:39:36
这是故意的。“文件”的内容可能不能作为文件使用。请记住,您正在处理的类和资源可能是JAR文件或其他类型资源的一部分。类加载器不必提供资源的文件句柄,例如,jar文件可能没有扩展到文件系统中的单个文件中。
通过获取java.io.File可以完成的任何操作都可以通过将流复制到临时文件中并执行相同的操作来完成,如果java.io.File是绝对必要的话。
发布于 2013-01-31 03:58:04
加载资源时,请注意以下各项之间的区别:
getClass().getClassLoader().getResource("com/myorg/foo.jpg") //relative path
和
getClass().getResource("/com/myorg/foo.jpg")); //note the slash at the beginning
我想,这种混乱导致了加载资源时出现的大多数问题。
此外,当您加载图像时,使用getResourceAsStream()
会更容易
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/com/myorg/foo.jpg"));
当您确实需要从JAR归档文件中加载(非图像)文件时,您可以尝试这样做:
File file = null;
String resource = "/com/myorg/foo.xml";
URL res = getClass().getResource(resource);
if (res.getProtocol().equals("jar")) {
try {
InputStream input = getClass().getResourceAsStream(resource);
file = File.createTempFile("tempfile", ".tmp");
OutputStream out = new FileOutputStream(file);
int read;
byte[] bytes = new byte[1024];
while ((read = input.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.close();
file.deleteOnExit();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} else {
//this will probably work in your IDE, but not from a JAR
file = new File(res.getFile());
}
if (file != null && !file.exists()) {
throw new RuntimeException("Error: File " + file + " not found!");
}
发布于 2014-11-26 20:29:38
答案只有一行:
String path = this.getClass().getClassLoader().getResource(<resourceFileName>).toExternalForm()
基本上,getResource
方法给出了URL。您可以通过调用toExternalForm()
从这个URL中提取路径。
https://stackoverflow.com/questions/941754
复制相似问题