在jar中运行时从资源文件夹获取文件名列表

时间:2017-12-12 14:52:45

标签: java jar fileinputstream

我在文件夹" resource / json / templates"中有一些Json文件。我想阅读这些Json文件。到目前为止,下面的代码片段允许我在IDE中运行程序时这样做,但是当我在jar中运行它时它会失败。

  JSONParser parser = new JSONParser();
  ClassLoader loader = getClass().getClassLoader();
  URL url = loader.getResource(templateDirectory);
  String path = url.getPath();
  File[] files = new File(path).listFiles();
  PipelineTemplateRepo pipelineTemplateRepo = new PipelineTemplateRepoImpl();
  File templateFile;
  JSONObject templateJson;
  PipelineTemplateVo templateFromFile;
  PipelineTemplateVo templateFromDB;
  String templateName;


  for (int i = 0; i < files.length; i++) {
    if (files[i].isFile()) {
      templateFile = files[i];
      templateJson = (JSONObject) parser.parse(new FileReader(templateFile));
      //Other logic
    }
  }
}
catch (Exception e) {
  e.printStackTrace();
}

非常感谢任何帮助。

非常感谢。

2 个答案:

答案 0 :(得分:1)

首先,请记住Jars是Zip文件,因此如果不解压缩,就无法从中获取单个File。 Zip文件并不完全具有目录,因此它不像获取目录的子项那么简单。

这有点困难,但我也很好奇,经过研究后我得到了以下内容。

首先,您可以尝试将资源放入嵌套在Jar中的平面Zip文件(resource/json/templates.zip),然后从该zip文件加载所有资源,因为您知道所有zip条目都是您想要的资源。这甚至可以在IDE中使用。

String path = "resource/json/templates.zip";
ZipInputStream zis = new ZipInputStream(getClass().getResourceAsStream(path));
for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
    // 'zis' is the input stream and will yield an 'EOF' before the next entry
    templateJson = (JSONObject) parser.parse(zis);
}

或者,您可以获取正在运行的Jar,遍历其条目,并收集resource/json/templates/的子项,然后从这些条目中获取流。注意:这仅在运行Jar 时有效,在IDE中运行时添加一个检查以运行其他内容。

public void runOrSomething() throws IOException, URISyntaxException {
    // ... other logic ...
    final String path = "resource/json/templates/";
    Predicate<JarEntry> pred = (j) -> !j.isDirectory() && j.getName().startsWith(path);

    try (JarFile jar = new Test().getThisJar()) {
        List<JarEntry> resources = getEntriesUnderPath(jar, pred);
        for (JarEntry entry : resources) {
            System.out.println(entry.getName());
            try (InputStream is = jar.getInputStream(entry)) {
                // JarEntry streams are closed when their JarFile is closed,
                // so you must use them before closing 'jar'
                templateJson = (JSONObject) parser.parse(is);
                // ... other logic ...
            }
        }
    }
}


// gets ALL the children, not just direct
// path should usually end in backslash
public static List<JarEntry> getEntriesUnderPath(JarFile jar, Predicate<JarEntry> pred)
{
    List<JarEntry> list = new LinkedList<>();
    Enumeration<JarEntry> entries = jar.entries();

    // has to iterate through all the Jar entries
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        if (pred.test(entry))
            list.add(entry);
    }
    return list;
}


public JarFile getThisJar() throws IOException, URISyntaxException {
    URL url = getClass().getProtectionDomain().getCodeSource().getLocation();
    return new JarFile(new File(url.toURI()));
}

我希望这会有所帮助。

答案 1 :(得分:0)

假设在类路径中,在jar中,目录以/ json(/ resource是根目录)开头,它可以是这样的:

    URL url = getClass().getResource("/json");
    Path path = Paths.get(url.toURI());
    Files.walk(path, 5).forEach(p -> System.out.printf("- %s%n", p.toString()));

这会使用jar:file://...网址,并在其上打开虚拟文件系统。

检查jar确实使用了该路径。

可以根据需要进行阅读。

     BufferedReader in = Files.newBufferedReader(p, StandardCharsets.UTF_8);