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?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
digiarnie
  • 22,305
  • 31
  • 78
  • 126

1 Answers1

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();
Kevin
  • 30,111
  • 9
  • 76
  • 83
  • you could just use .getResourceAsStream() :) – Cogsy Jan 21 '09 at 03:33
  • 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 Jan 21 '09 at 04:22
  • 1
    Furthermore, is there any significance to the 4096? – digiarnie Jan 21 '09 at 23:37