final public class ResourceLoader {
public static byte[] getResource(String path) {
JarFile jarFile = new JarFile(URLDecoder.decode(ResourceLoader.class.getProtectionDomain().getCodeSource().getLocation().getFile()));
JarEntry entry = jarFile.getJarEntry(path);
byte[] data = new byte[(int)entry.getSize()];
BufferedInputStream in = new BufferedInputStream(jarFile.getInputStream(entry));
in.read(data);
in.close();
return data;
}
}
这样直接用 ResourceLoader.getResource(”data/data.dat”) 就可以读取 jar 文件中 data 目录下的 data.dat 文件了。这里静态方法 getResource 的 path 参数是相对于 Jar 文件来说的相对路径。