Several Ways of Copying a file in Java

Java offers several libraries for file operations:

  • Java.io.File (Using FileStreams)

  • Java.nio.channels.FileChannel (Using FileChannels)

  • Java.nio.file.Files (Using Java 7 Files Class)

  • Org.apache.commons.io.FileUtils (Using Apache Commons IO)


1. Copy file using FileStreams


This is one of the most common ways of copying the file content from one to another. It is basically usingfileInputStream to read contents of the file and write them into a buffer then from buffer it writes content to new file using fileOutputStream.

Here how it works:
public static void copyFileUsingFileStreams(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// input stream, reads the content of a file
// instantiate the file input stream from source file
InputStream input = new FileInputStream(source);

// create an output stream that writes the content of a file
// instantiate the file output stream from destination file
OutputStream output = new FileOutputStream(destination);

// create a byte array for reading
byte[] buffer = new byte[1024];
// create an integer to determine how many bytes going to be readed
int length;

// Reading up the information from the source file
// to fill the byte array (up to 1024 bytes)
// return total number of bytes in actual to variable length
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length); // write content to the buffer
}
// close the streams
input.close();
output.close();
System.out.println("File copied!");
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

2. Copy file using FileChannels


Using channels said to be faster in documentation of Java.NIO. In order to use channels, transferFrom method needs to be called.

Here is an example:
public static void copyFileUsingFileChannels(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// instantiate the file input stream from source file
FileChannel inputChnl = new FileInputStream(source).getChannel();

// instantiate the file output stream from destination file
FileChannel outputChnl = new FileOutputStream(destination).getChannel();

// write from input channel to output channel, starting from 0 byte until its size
outputChnl.transferFrom(inputChnl,0,inputChnl.size());

// close the channels
inputChnl.close();
outputChnl.close();
System.out.println("File copied!");
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

3. Copy file using Java 7 Files Class


Using Java 7 SE library, you can copy files with Copy method located in Java.nio.file.Files class.

Here how it is:
public static void copyFileUsingJava7(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// single line of code to copy content of one file to another
Files.copy(source.toPath(),destination.toPath());
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

4. Copy file using Apache Commons IO


Copying of content from one file to another can be handled by copyFile() method of FileUtils class in Apache Commons IO API. This class is actually using Java NIO API’s FileChannel class.

Here is an example:
public static void copyFileUsingApacheCommons(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// single line of code to copy content of one file to another
FileUtils.copyFile(source, destination);
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

Which way is the fastest?


Let’s see which method is the fastest. In order to do that we need to create four files with exactly same content but different names. Then, we will copy each file with four different ways we mentioned.
package com.sirma.files;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.text.DecimalFormat;

/**
* Created by ismailsirma on 20.6.2015.
*/
public class CopyFileFast {

public static void main(String[] args) throws InterruptedException,
IOException {
long initialtime = System.nanoTime();
long starttime;
DecimalFormat f = new DecimalFormat("0.00000");

// Copy the file using FileStreams
File source = new File("C:\\\\Trial\\\\sourcefile1.txt");
File destination = new File("C:\\\\Trial\\\\destinationfile1.txt");
starttime = System.nanoTime();
copyFileUsingFileStreams(source, destination);
double timeelapsed = (double) (System.nanoTime() - starttime);
double timeelapsedsec = timeelapsed/1000000000;
System.out.println("Time elapsed with FileStream is " + f.format(timeelapsedsec) + " seconds");

// Copy the file using FileChannels
source = new File("C:\\\\Trial\\\\sourcefile2.txt");
destination = new File("C:\\\\Trial\\\\destinationfile2.txt");
starttime = System.nanoTime();
copyFileUsingFileChannels(source, destination);
timeelapsed = (double) (System.nanoTime() - starttime);
timeelapsedsec = timeelapsed/1000000000;
System.out.println("Time elapsed with FileChannel is " + f.format(timeelapsedsec) + " seconds");

// Copy the file using Java 7 File Class
source = new File("C:\\\\Trial\\\\sourcefile3.txt");
destination = new File("C:\\\\Trial\\\\destinationfile3.txt");
starttime = System.nanoTime();
copyFileUsingJava7(source, destination);
timeelapsed = (double) (System.nanoTime() - starttime);
timeelapsedsec = timeelapsed/1000000000;
System.out.println("Time elapsed with Java 7 NIO Files Class is " + f.format(timeelapsedsec) + " seconds");

// Copy the file using Apache Commons IO
source = new File("C:\\\\Trial\\\\sourcefile4.txt");
destination = new File("C:\\\\Trial\\\\destinationfile4.txt");
starttime = System.nanoTime();
copyFileUsingApacheCommons(source, destination);
timeelapsed = (double) (System.nanoTime() - starttime);
timeelapsedsec = timeelapsed/1000000000;
System.out.println("Time elapsed with Apache Commons IO is " + f.format(timeelapsedsec) + " seconds");

// calculating the total time taken
double initialtimed = (double) initialtime;
double finaltime = (double) System.nanoTime();
finaltime = finaltime/1000000000;
initialtimed = initialtimed/1000000000;
System.out.println("Total elapsed time is " + f.format(finaltime - initialtimed) + "seconds");
}

public static void copyFileUsingFileStreams(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// input stream, reads the content of a file
// instantiate the file input stream from source file
InputStream input = new FileInputStream(source);

// create an output stream that writes the content of a file
// instantiate the file output stream from destination file
OutputStream output = new FileOutputStream(destination);

// create a byte array for reading
byte[] buffer = new byte[1024];
// create an integer to determine how many bytes going to be read
int length;

// Reading up the information from the source file
// to fill the byte array (up to 1024 bytes)
// return total number of bytes in actual to variable length
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length); // write content to the buffer
}
// close the streams
input.close();
output.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

public static void copyFileUsingFileChannels(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// instantiate the file input stream from source file
FileChannel inputChnl = new FileInputStream(source).getChannel();

// instantiate the file output stream from destination file
FileChannel outputChnl = new FileOutputStream(destination).getChannel();

// write from input channel to output channel, starting from 0 byte until its size
outputChnl.transferFrom(inputChnl,0,inputChnl.size());

// close the channels
inputChnl.close();
outputChnl.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

public static void copyFileUsingJava7(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// single line of code to copy content of one file to another
Files.copy(source.toPath(),destination.toPath());
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

public static void copyFileUsingApacheCommons(File source, File destination){

// try - catch for handling IO and File Not Found Exceptions
try {
// single line of code to copy content of one file to another
FileUtils.copyFile(source, destination);
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

}

Results


Time elapsed with FileStream is 0,00078 seconds
Time elapsed with FileChannel is 0,00447 seconds
Time elapsed with Java 7 NIO Files Class is 0,00711 seconds
Time elapsed with Apache Commons IO is 0,00532 seconds
Total elapsed time is 0,03588 seconds

Share this Post

Categories

Featured Author