2

I've already looked at many other questions that are similar to mine, but unfortunately none of their answers have so far worked.

I have a Java project that looks like this:

 MyProject/ src/ abc/ MyClass.java xyz/ file1.txt file2.txt ... 

Essentially, I'm trying to read all of the txt files above in MyClass.java. This is what I'm currently doing:

File dir = new File("src/xyz/"); for (File child : dir.listFiles()) { ... } 

This works fine until I put everything into a JAR format, at which point dir.listFiles() returns null and the above no longer works. Is there anyway I can still read these txt files even when they are packed into a JAR? Also, I am using Eclipse if it makes any difference.

2 Answers 2

8

You can access files on your classpath via the classloader.

getClass().getResourceAsStream("/xyz/file1.txt"); 

Then you would use the InputStream as usual. Note that I use absolute path, but relative to the current package works as well.

Since Java 6 it is also possible to list all the resources under a package quite easily:

 Enumeration urls = getClass().getClassLoader().getResources("xyz"); urls.nextElement().openStream(); 
Sign up to request clarification or add additional context in comments.

4 Comments

This requires that /xyz/file1.txt is included in the JAR. This may require modifying build properties or the equivalent.
Good answer. Happy 1K. :)
Thanks :) Also added a way to get all the resources under a package.
Thanks for your reply, although Class doesn't seem to have a getResources method.
1

Is there anyway I can still read these txt files even when they are packed into a JAR?

Given you mean 'without knowing their names in advance' no.

OTOH you can include a resource at a known location in a Jar and list the possibles texts in that. Path from root or class-path, one per line would work well. Gain an URL to the resource using something like:

URL url = this.getClass().getResource("/path/to/the.resource"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.