How to copy a file in Java

By Alvin Alexander. Last updated: October 18, 2016

The easiest way to copy a file in Java is to download the Apache Commons IO library; just download their library, then use the methods of their FileUtils class to copy a file.

However, if you're just as interested in the technical details of how to copy a file in Java, or just want a method to copy a file in Java, the method below, taken from my Java file utilities class, shows how this actually works:

public static void copyFile(File source, File destination) throws IOException
{
 byte[] buffer = new byte[100000];
 BufferedInputStream bufferedInputStream = null;
 BufferedOutputStream bufferedOutputStream = null;
 try
 {
 bufferedInputStream = new BufferedInputStream(new FileInputStream(source));
 bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destination));
 int size;
 while ((size = bufferedInputStream.read(buffer)) > -1)
 {
 bufferedOutputStream.write(buffer, 0, size);
 }
 }
 catch (IOException e)
 {
 // TODO may want to do something more here
 throw e;
 }
 finally
 {
 try
 {
 if (bufferedInputStream != null)
 {
 bufferedInputStream.close();
 }
 if (bufferedOutputStream != null)
 {
 bufferedOutputStream.flush();
 bufferedOutputStream.close();
 }
 }
 catch (IOException ioe)
 {
 // TODO may want to do something more here
 throw ioe;
 }
 }
}

As you can see this is pretty straightforward. Just open a BufferedInputStream and a BufferedOutputStream and read from the first and write to the second. As you might guess, you use these buffered streams so you can treat the file contents as a series of bytes.

There is probably a better way to choose the buffer size than what I have shown here, but I've never dug into those details.

Java file copying references

Again, if you're going to be doing a lot of Java file reading, writing, copying, and deleting, take a look at the Apache Commons IO library.

As mentioned, if you're more interested in understanding how Java file utilities work, I also encourage you to take a look at my Java file utilities class.

I first developed these file utilities when I wrote a lot of Java Swing code many years ago, and (a) I don't remember the Commons IO library being available, and (b) if they were available, I was opposed to shipping a 1.2MB jar file with my Swing applications just to read, write, copy, and delete files. These days 1.2MB seems trivial, but at that time, when users were downloading my Java/Swing apps over slow internet connections, it was a pretty big deal.

alvinalexander.com
is owned and operated by
Valley Programming, LLC

In regards to links to Amazon.com, As an Amazon Associate
I (Valley Programming, LLC) earn from qualifying purchases

This website uses cookies: learn more

AltStyle によって変換されたページ (->オリジナル) /