JavaPro123
JavaPro123

Reputation: 35

Get all files inside directory's in jar file in java

Lets say the location of my project is "some/random/guy", and inside the project there is a directory located with the path "some/random/guy/versions", I want to get all files/directory's inside that folder so I can get all the availible versions. But the versions dir only gets created once the project is compiled, so its not in my IDE.

After searching like 2 hours already I couldn't find my answer.

Currently Im using the code from oracle docs but it also doesn't work:

try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("some/random/guy/versions"))) {
        for (Path file: stream) {
            System.out.println(file.getFileName());
        }
    } catch (IOException | DirectoryIteratorException e) {
        System.err.print(e);
    }

How can I get all files/directory's inside any folder thats located inside a jar file?

I would like to avoid unzipping the jar file if possible, thanks.

Upvotes: 2

Views: 259

Answers (2)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

jar file is plain old zip archive. You do not neet unzip jar to get all entries' names, because zip files contains CentralDirectory. All you need is to use standard ZipInputStream or one of framework, e.g. zip4jvm:

import ru.olegcherednik.zip4jvm.ZipMisc;

public static List<String> getAllEntryNames(Path jar) throws IOException {
    return ZipMisc.zip(jar).getEntries()
                  .map(ZipFile.Entry::getFileName)
                  .collect(Collectors.toList());
}

This snippet retrieves all existed entry names. Directory (if they exists as separate entry) ends with /.

Upvotes: 0

DuncG
DuncG

Reputation: 15086

This code will show contents of any jar/zip archive using NIO FileSystem handling, you need to pass in a location of the jar and optional path under the jar:

public static void main(String[] args) throws IOException {
    Path jar = Path.of(args[0]);
    String relPath = args.length > 1 ? args[1] : "/";

    System.out.println("ZIP/JAR: "+jar+" isRegularFile()="+Files.isRegularFile(jar));

    try (FileSystem fs = FileSystems.newFileSystem(jar)) {
        Path path = fs.getPath(relPath);
        System.out.println("SCAN "+ jar+" starting at path: "+path);

        try(Stream<Path> str = Files.find(path, Integer.MAX_VALUE, (p,a) -> true)) {
            str.forEach(System.out::println);
        }
    }
}

Upvotes: 1

Related Questions