Skip to content
Advertisement

Read directory inside JAR with InputStreamReader

So, this question has been asked a million times i believed and I’ve been reading them for a couple of hours and trying several options given by some people but none of them work for me.

I want to list all the files inside a directory inside the application’s JAR, so in IDE this works:

JavaScript

That gives me all the files inside the directory.

Now, i’ve tried this also:

JavaScript

And from IDE it prints ALL the files in the directory. Outside IDE prints: “END OF LINE”.

Now, I can find an entry inside a Jar with this too:

JavaScript

That’s some horrible coding i had to do to that String.

Anyway… I can’t get the list of resources inside the “resources” directory within the Jar… How can I do this???

Advertisement

Answer

There’s no way to simply get a filtered list of internal resources without first enumerating over the contents of the Jar file.

Luckily, that’s actually not that hard (and luckily for me you’ve done most of the hardwork).

Basically, once you have a reference to the JarFile, you simple need to ask for its’ entries and iterate over that list.

By checking the JarEntry name for the required match (ie resources), you can filter the elements you want…

For example…

JavaScript

Caveat

This type of question actually gets ask a bit. Rather then trying to read the contents of the Jar at runtime, it would be better to produce some kind of text file which contained a list of the available resources.

This could be produced by your build process dynamically before the Jar file is created. It would be a much simpler solution to then read this file in (via getClass().getResource(), for example) and then look up each resource list in the text file…IMHO

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement