Jar文件本质上是带有清单的Zip文件。
Jar /
Zip文件实际上不像磁盘那样具有目录概念。它们只是具有名称的条目列表。这些名称可能包含某种路径分隔符,并且某些条目实际上可能被标记为目录(并且往往没有与之关联的任何字节,仅充当标记)
如果要查找给定路径中的所有资源,则必须打开Jar文件并亲自检查其条目,例如…
JarFile jf = null;try { String path = "resources"; jf = new JarFile(new File("dist/ResourceFolderCounter.jar")); Enumeration<JarEntry> entries = jf.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (!entry.isDirectory()) { String name = entry.getName(); name = name.replace(path + "/", ""); if (!name.contains("/")) { System.out.println(name); } } }} catch (IOException ex) { try { jf.close(); } catch (Exception e) { }}现在,这需要您知道要使用的Jar文件的名称,这可能会出现问题,因为您可能希望列出许多不同的Jar中的资源…
更好的解决方案是在构建时生成某种“资源查找”文件,其中包含您可能需要的所有资源名称,甚至可能输入特定名称。
这样您可以简单使用…
BufferedReader reader = null;try { reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsInputStream("/resources/MasterResourceList.txt"))); String name = null; while ((name = br.readLine()) != null) { URL url = getClass().getResource(name); }} finally { try { br.close(); } catch (Exception exp) { }}例如…
您甚至可以为文件添加资源数量;)



