扫描JAR中的文件夹

时间:2012-02-27 05:37:59

标签: java jar uri inputstream relative-path

已经提出了许多类似的问题,但在我不得不自己提出问题之前,我只能忍受很多痛苦。

无论如何,我在 jar file / input中有文件,我需要读取该文件夹中文件名的列表(稍后,自己阅读文件。)

尝试#1:

String path Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
// "/Applications/company/extensions/components/Box/Box/Box.jar"
String decoded = URLDecoder.decode(path, "UTF-8");
// "/Applications/company/extensions/components/Box/Box/Box.jar"
File[] files = (new File(decoded + "/input")).listFiles();
// files = null (bad)

尝试#2:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("input");
// url.file: "file:/Applications/company/extensions/components/Box/Box/Box.jar!/input"
// url.path: (ditto)
// url.protocol: "jar"
// url.host: ""
// url.query: null
// url.port: -1
java.net.URI uri = new java.net.URI(url.getProtocol(), url.getAuthority(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
// URISyntaxException --> "Relative path in absolute URI" (bad)

中间的其他杂项尝试具有相同的结果。我根本无法读取那个罐子里的文件夹...

有人知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

也许我误解了你的问题,但...... 考虑使用java.util.jar包?

以下是一个示例:Showing jar file content

希望这有帮助

答案 1 :(得分:0)

根据How do I list the files inside a JAR file?

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL jar = src.getLocation();
  ZipInputStream zip = new ZipInputStream(jar.openStream());
  /* Now examine the ZIP file entries to find those you care about. */
  ...
} 
相关问题