Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a text file from a jar into a file outside of the jar?

Tags:

java

file

io

jar

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?

like image 216
digiarnie Avatar asked Dec 31 '22 06:12

digiarnie


1 Answers

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();
like image 51
Kevin Avatar answered Jan 04 '23 15:01

Kevin