tags:

views:

245

answers:

1

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?

+6  A: 

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();
Kevin
you could just use .getResourceAsStream() </nitpick> :)
Cogsy
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)
digiarnie
Furthermore, is there any significance to the 4096?
digiarnie