In Java, copying a file is a common operation for creating backups or storing the content at multiple locations. Java provides different public classes, libraries, built-in functions, or third-party tools for copying files. For instance, you can read the data in Streams or bytes, use instances such as copy() or copyFile(), etc. This article consists of several different methods for copying a file in Java.
Quick Outline
This article covers the following methods of copying a file in Java:
- Method 1: Copy the File Using java.nio Package
- Method 2: Copy the File Using FileInputStream and FileOutputStream Class
- Method 3: Copy the File Using FileChannel Class
- Method 4: Copy the File Using Apache Commons IO Library
- Method 5: Copy the File Using the Guava Library
Method 1: Copy the File Using java.nio Package
The java.nio package provides multiple classes for creating and manipulating files. It is considered efficient and faster than the traditional IO package. The “java.nio” package uses Buffers and Channels that improve the performance of the package as compared to the Stream class of the IO package.
This code imports the “java.nio.file” and “java.io” packages via the following import statements. These packages will provide classes like Files and Path for file handling and IOException class for exception handling:
import java.io.IOException;
import java.nio.file.*;
Inside the try block, the Path objects “sourceFile” and “destFile” are created using the Paths.get() method. The get() method accepts the source and destination files’ paths as parameters. The Files class invokes the static function i.e., copy() method that accepts three arguments i.e., source path, destination path, and the optional parameter. The “StandardCopyOption.Replace_Exisiting” indicates that in case the destination file already exists, it will be replaced. The print statement then displays the corresponding results:
try {
Path sourceFile=Paths.get("C:\\Users\\Desktop\\sourceFile.txt");
Path destFile=Paths.get("C:\\Users\\Desktop\\destFile.txt");
Files.copy(sourceFile,destFile,StandardCopyOption.REPLACE_EXISTING);
System.out.println("The file is Successfully Copied");
}
The catch block catches and displays the IOException class object “e”. The “e” object is printed that describes the exception that has occurred:
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
Method 2: Copy the File Using FileInputStream and FileOutputStream Class
The FileInputStream reads the data from the source in the form of a stream of bytes. On the other hand, the FileOutputStream writes the data to the destination in the byte stream. The objects of these classes invoke the methods that read and write the data and hence help in copying the content of a file.
In the given code, the import statement includes the necessary dependencies, classes, and methods from the java.io package:
import java.io.*;
Inside the try block, the two File objects “sourceFile” and “destinationFile” are created that accept the source file’s path and the destination file’s path as parameters in the constructors:
try
{
File sourceFile=new File("C:\\Users\\Desktop\\sourceFile.txt");
File destinationFile=new File("C:\\Users\\Desktop\\destFile.txt");
The “inputStream” and “outputStream” are the two objects of the InputStream and OuptutStream classes. The byte array “byteArray” is created with the given size and an integer variable “length” is also created:
InputStream inputStream = new FileInputStream(sourceFile);
OutputStream outputStream = new FileOutputStream(destinationFile);
byte [ ] byteArray = new byte[4096];
int length = 0;
In the while loop, the read() method reads from the inputStream. The loop continues to execute unless the length is greater than “-1”. The “length” variable stores the total bytes returned by the read() method. The “-1” indicates that there is no more content to be read. The write() method writes the source file’s content to the outputStream that contains the destination file’s path. After the execution of the loop, the println() function displays the following message:
while ( (length = inputStream.read(byteArray)) > -1)
{
outputStream.write(byteArray, 0, length);
outputStream.flush();
}
System.out.println("This file is successfully");
}
The catch block catches and displays any IOException that may occur during the normal flow of the program:
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
Method 3: Copy the File Using FileChannel Class
The FileChannel class from the “java.nio” package provides the method to read or write a file from a specific point within the file. The FileChannel class provides an asynchronous approach to file directories which makes it more efficient than the IO package classes.
The following import statement includes the classes from the java.io and java.nio.channels package:
import java.io.*;
import java.nio.channels.*;
The File class creates a source and destination object i.e., “sourceFile” and “destinationFile”. The source file’s path and destination file’s path are passed to the constructor for reading and writing operations:
File sourceFile = new File("C:\\Users\\Desktop\\sourceFile.txt");
File destinationFile = new File ("C:\\Users\\Desktop\\destFile.txt");
The FileInputStream object reads the file’s content from the given object. Similarly, the FileOutputStream object will write the data to the specified file:
try
{
FileInputStream inputStream=new FileInputStream(sourceFile);
FileOutputStream outputStream = new FileOutputStream(destinationFile);
The “inFileChannel” and “outFileChannel” are the two instances of the FileChannel classes:
FileChannel inFileChannel = inputStream.getChannel();
FileChannel outFileChannel = outputStream.getChannel();
The “inFileChannel” object will invoke the transferTo() method. It will continue to iterate over the file’s content and the loop terminates when the file size exceeds. The content that is read is then written to the outFileChannel. After the operation is successful, the print statement is executed:
inFileChannel.transferTo(0, inFileChannel.size(), outFileChannel);
System.out.println("File is Successfully Copied");
}
The catch block throws any exception that occurs during the normal execution of the code:
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
Method 4: Copy the File Using Apache Commons IO Library
Apache Commons IO is a third-party library that is used for file handling in Java. The FileUtils class of the ApacheCommons IO provides a bunch of static functions for creating, modifying, or manipulating files or directories in Java.
To utilize the FileUtils static method for copying a file, add the following dependency in the “pom.xml” or “build.gradle” inside your project directory:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
Here, the dependency has been added to the “pom.xml” file of the Maven project:
In the main program, provide the following import statements to include the File, IOException, and FileUtils classes from the java.io and apache.commons.io packages:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
Within the main() method, the File class is used to create two objects i.e., “srcFile” and “destFile”. The “srcFile” is provided with the path of the source file to read from and the “destFile” is provided the path of the file to write to:
File srcFile = new File("C:\\Users\\Desktop\\sourceFile.txt");
File destFile = new File("C:\\Users\\Desktop\\destFile.txt");
The FileUtils class invokes the static function copyFile() inside the try block. It accepts two arguments i.e., srcFile and destFile. The print statement then displays the following message:
try
{
FileUtils.copyFile(srcFile, destFile);
System.out.println("File has been Copied Successfully");
}
The catch block creates the “e” object of the IOException class. The exception object describes the error description in the print statement:
catch(IOException e)
{
System.out.println(e);
}
Complete Code & Output
Method 5: Copy the File Using the Guava Library
The Guava is an open-source library that enhances the functionality of the Java language. It is provided by Google as a core library with multiple utilities and classes to simplify the code functionality.
To get started with the Guava library for copying the file in Java, add the following dependency to the “pom.xml” or “build.gradle” file of your project:
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
</dependencies>
The dependency is added to the pom.xml file:
Use the following import statement for using the methods of the File class of the java.io package:
import java.io.File;
The two objects of the File class “sourceFile” and “destFile” are created. The source and destination file’s path are passed to the object’s constructor:
File sourceFile = new File("C:\\Users\\Desktop\\sourceFile.txt");
File destFile = new File("C:\\Users\\Desktop\\destFile.txt");
Inside the try block, the Files class invokes the static copy() function that takes two arguments i.e., source and target. After the execution of the copying code, the print statement displays the following message indicating that the operation has been successful:
try {
com.google.common.io.Files.copy(sourceFile, destFile);
System.out.println("Successfully copied");}
The IOException exceptions might occur during the normal flow of the code, which will be caught by the catch block:
catch(IOException e){
System.out.println(e);}
Complete Code & Output
This sums up different methods for copying a file in Java.
Conclusion
The Java file copy operations can be performed by using public classes, built-in methods, third-party libraries, or different packages as shown in this guide. For copying a file in Java, there are several factors that can impact the performance of this operation such as file size, type, etc. This article is a practical guide that discusses various methods for copying a file in Java.