4

Let's say I have a file called test.txt within the package "com.test.io" within my jar.

How would I go about writing a class which retrieves this text file and then copies the contents to a new file on the file system?

1 Answer 1

10

Assuming said jar is on your classpath:

URL url = getClassLoader().getResource("com/test/io/test.txt"); FileOutputStream output = new FileOutputStream("test.txt"); InputStream input = url.openStream(); byte [] buffer = new byte[4096]; int bytesRead = input.read(buffer); while (bytesRead != -1) { output.write(buffer, 0, bytesRead); bytesRead = input.read(buffer); } output.close(); input.close(); 
Sign up to request clarification or add additional context in comments.

3 Comments

you could just use .getResourceAsStream() </nitpick> :)
thanks for that information. I was thinking of doing something like that however I thought I may have missed something simpler, kind of like using something from apache commons io fileutils (or something similar)
Furthermore, is there any significance to the 4096?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.