简体   繁体   中英

Random file from a folder inside JAR

I want to get a random image from a specific folder in Java. The code does already work inside the Eclipse IDE, but not in my runnable JAR. Since images inside the JAR file are not files, the code below results in a NullPointerException, but I'm not sure how to "translate" the code so that it will work in a runnable JAR.

final File dir = new File("images/");
File[] files = dir.listFiles();
Random rand = new Random();
File file = files[rand.nextInt(files.length)];

If the given path is invalid then listFiles() method reutrns null value. So you have to handle it if the path is invalid. Check below code:

    final File dir = new File("images/");
    File[] files = dir.listFiles();
    Random rand = new Random();
    File file = null;
    if (files != null) {
        file = files[rand.nextInt(files.length)];
    }

If the jar is to contain the images then (assuming a maven or gradle project) they should be in the resources directory (or a subdirectory thereof). These images are then indeed no 'Files' but 'Resources' and should be loaded using getClass().getResource(String name) or getClass.getResourceAsStream(String name) .

You could create a text file listing the resource paths of the images. This would allow you to simply read all lines from that file and access the resource via Class.getResource .

You could even create such a list automatically. The following works for my project type in eclipse; some minor adjustments may be needed for your IDE.

private static void writeResourceCatalog(Path resourcePath, Path targetFile) throws IOException {
    URI uri = resourcePath.toUri();
    try (BufferedWriter writer = Files.newBufferedWriter(targetFile, StandardCharsets.UTF_8)) {
        Files.list(resourcePath.resolve("images")).filter(Files::isRegularFile).forEach(p -> {
            try {
                writer.append('/').append(uri.relativize(p.toUri()).toString()).append('\n');
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
writeResourceCatalog(Paths.get("src", "main", "resources"), Paths.get("src", "main", "resources", "catalog.txt"));

After building the jar with the new file included you could simply list all the files as

List<URL> urls = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(WriteTest.class.getResourceAsStream("/catalog.txt"), StandardCharsets.UTF_8))) {
    String s;
    while ((s = reader.readLine()) != null) {
        urls.add(SomeType.class.getResource(s));
    }
}

这似乎是一个路径问题,如果尝试图像目录的绝对路径或为 java 配置设置 maon 目录,也许会起作用

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM