Reputation: 431
I want to copy file to another directory.I know this has been asked million times,I read tons of answers about this but I just can't seem to make it work.This is the code I am currently using:
copyFile(new File(getClass().getResource("/jars/TurnOffClient.jar").toString()),
new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
And this is the method:
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
This is my dir: Directories http://imageshack.com/a/img820/6418/5g3m.png
////////////////////////////////////////////////////////////////////////////////////////// And this is the exception I get:
Upvotes: 1
Views: 68
Reputation: 16987
Standard ways to copy a file don't work because you are trying to copy the file out of the JAR. When you get a file out of a JAR, you can't get a File
object for it. You can get a URL
, and from that an InputStream
.
An existing answer includes code to copy data from one input stream to another. Here it is, adapted for the file inside a JAR:
InputStream in = getClass().getResourceAsStream("/jars/TurnOffClient.jar");
OutputStream out = new FileOutputStream(new File("C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup\\karioc.jar"));
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
Upvotes: 2
Reputation: 691
Have you tried using java.nio.Files.copy(); ? There's built in methods for doing this.
If that doesn't work then go ahead and transfer bytes from a file inputstream to an output file stream.
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
As described here: Standard concise way to copy a file in Java?
Upvotes: 0