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 source, File destinationDirectory)'

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 = > 0) {
out.write(buf, 0, len);

As long as the files are on the same volume, you just need to use the 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.


Popular posts from this blog

Vim vi how to reload a file your editing