Four ways to copy files in Java

  • 2020-04-01 04:04:20
  • OfStack

Although Java provides an IO action class that can handle files, there is no way to copy files. Copying files is an important operation when your program has to deal with many files. However, there are several ways to do Java file copying, and here are the most popular in 4.

1. Use FileStreams to copy

This is the classic way to copy the contents of one file to another. Use the FileInputStream to read the bytes of file A, and use the FileOutputStream to write to file B. Here is the code for the first method:


private static void copyFileUsingFileStreams(File source, File dest)
    throws IOException {  
  InputStream input = null;  
  OutputStream output = null;  
  try {
      input = new FileInputStream(source);
      output = new FileOutputStream(dest);    
      byte[] buf = new byte[1024];    
      int bytesRead;    
      while ((bytesRead = input.read(buf)) > 0) {
        output.write(buf, 0, bytesRead);
      }
  } finally {
    input.close();
    output.close();
  }
}

As you can see we perform several read and write operations on try's data, so this should be an inefficient one. The next method we'll see is a new one.

2. Copy with a FileChannel

Java NIO includes the transferFrom method, which should be copied faster than the file stream, depending on the document. Here is the code for the second method:


private static void copyFileUsingFileChannels(File source, File dest) throws IOException {  
    FileChannel inputChannel = null;  
    FileChannel outputChannel = null;  
  try {
    inputChannel = new FileInputStream(source).getChannel();
    outputChannel = new FileOutputStream(dest).getChannel();
    outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
  } finally {
    inputChannel.close();
    outputChannel.close();
  }
}


3. Copy using Commons IO

Apache Commons IO provides a copy file method in its FileUtils class that can be used to copy a file to another place. It is very convenient to use the Apache Commons FileUtils class when you are already using your project. Basically, this class USES Java NIO FileChannel inside. Here is the code for the third method:


private static void copyFileUsingApacheCommonsIO(File source, File dest)
    throws IOException {
  FileUtils.copyFile(source, dest);
}

4. Use Java7's Files class to copy

If you have some experience in Java 7 you may know that you can use the copy method of the Files class file to copy from one file to another. This is the code for the fourth method:


private static void copyFileUsingJava7Files(File source, File dest)
    throws IOException {  
    Files.copy(source.toPath(), dest.toPath());
}


5. Test

Now to see which of these methods is more efficient, we will copy a large file using each in a simple program. To avoid any performance visibility from the cache we will use four different source files and four different target files. Let's take a look at the code:


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import org.apache.commons.io.FileUtils;
 
public class CopyFilesExample {
 
  public static void main(String[] args) throws InterruptedException,
      IOException {
 
    File source = new File("C:\Users\nikos7\Desktop\files\sourcefile1.txt");
    File dest = new File("C:\Users\nikos7\Desktop\files\destfile1.txt");
 
    // copy file using FileStreams
    long start = System.nanoTime();
    long end;
    copyFileUsingFileStreams(source, dest);
    System.out.println("Time taken by FileStreams Copy = "
        + (System.nanoTime() - start));
 
    // copy files using java.nio.FileChannel
    source = new File("C:\Users\nikos7\Desktop\files\sourcefile2.txt");
    dest = new File("C:\Users\nikos7\Desktop\files\destfile2.txt");
    start = System.nanoTime();
    copyFileUsingFileChannels(source, dest);
    end = System.nanoTime();
    System.out.println("Time taken by FileChannels Copy = " + (end - start));
 
    // copy file using Java 7 Files class
    source = new File("C:\Users\nikos7\Desktop\files\sourcefile3.txt");
    dest = new File("C:\Users\nikos7\Desktop\files\destfile3.txt");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    end = System.nanoTime();
    System.out.println("Time taken by Java7 Files Copy = " + (end - start));
 
    // copy files using apache commons io
    source = new File("C:\Users\nikos7\Desktop\files\sourcefile4.txt");
    dest = new File("C:\Users\nikos7\Desktop\files\destfile4.txt");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    end = System.nanoTime();
    System.out.println("Time taken by Apache Commons IO Copy = "
        + (end - start));
 
  }
 
  private static void copyFileUsingFileStreams(File source, File dest)
      throws IOException {
    InputStream input = null;
    OutputStream output = null;
    try {
      input = new FileInputStream(source);
      output = new FileOutputStream(dest);
      byte[] buf = new byte[1024];
      int bytesRead;
      while ((bytesRead = input.read(buf)) > 0) {
        output.write(buf, 0, bytesRead);
      }
    } finally {
      input.close();
      output.close();
    }
  }
 
  private static void copyFileUsingFileChannels(File source, File dest)
      throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
      inputChannel = new FileInputStream(source).getChannel();
      outputChannel = new FileOutputStream(dest).getChannel();
      outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
      inputChannel.close();
      outputChannel.close();
    }
  }
 
  private static void copyFileUsingJava7Files(File source, File dest)
      throws IOException {
    Files.copy(source.toPath(), dest.toPath());
  }
 
  private static void copyFileUsingApacheCommonsIO(File source, File dest)
      throws IOException {
    FileUtils.copyFile(source, dest);
  }
 
}


Output:


Time taken by FileStreams Copy = 127572360
Time taken by FileChannels Copy = 10449963
Time taken by Java7 Files Copy = 10808333
Time taken by Apache Commons IO Copy = 17971677


As you can see, copying large files with FileChannels is the best way. If you work with larger files, you'll notice a bigger speed difference. This is an example that demonstrates four different methods in Java for copying a file.

The above is the entire content of this article, I hope to help you with your study.


Related articles: