加载资源时,请确保注意到以下两者之间的区别:
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!");
}