How to copy a file in Java

Java doesn't provide a copy method for files but it can be done.

A good way to do it is to use the
org.apache.commons.io.FileUtils.copyFileToDirectory(File source, File destinationDirectory)'

http://jakarta.apache.org/commons/io/

but here is a simple example using streams

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 long as the files are on the same volume, you just need to use the java.io.File.renameTo() method. Using this call for files and directories works equally well, but due to some platform-specific runtime implementation differences, this is one of those things that falls into the write once, test multiple places, and tweak until done catagories. This call will fail if you try to move a file from one volume to another.


http://developer.apple.com/qa/java/java21.html

Comments

Popular posts from this blog

Vim vi how to reload a file your editing