Java: copy file from jar resources

I was looking for a solution to copy file, build in to jar file to any external location.

Here is the solution, I came to:

String file = "config.xml";

File file = new File("C:\\"+file);

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(file);
OutputStream outputStream = null;
try {
// write the inputStream to a FileOutputStream
outputStream =
new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
System.out.println("Done!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
// outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}

significant help for this solution, I got from How To Convert InputStream To File In Java

Leave a Reply

%d bloggers like this: