Different Ways to Copy Files in Java


Java provides different ways to copy files including the ‘File’, ‘FileInputStream’ and‘FileOutputStream’ classes. There are times when we need to take a backup, compress a file or share it with others. In these situations, copying that file becomes necessary. Weare going to explore the methods and classes that will help us to copy the content of one file to another file through Java programs.

Before jumping to the example program directly, let’s discuss some classes and built-in methods that we will be using. This will build a foundation for understanding the code. Note that these classes and methods are associated with some exceptions too, therefore,it is necessary to define a catch block to handle those exceptions.

I/O Streams

Stream is an abstraction that is used while performing Input and Output operations in Java. Basically, the input streams are used to take input from sources like keyboard, disk files etc. The output streams refer to the destination where data gets displayed or written.

File Class

This is the class that represents path of files and directories in the form of Strings. We pass the paths inside its corresponding constructor as a parameter.

Syntax

File nameOfObject = new File("filePath");

FileInputStream Class

It is used to read the content of a file. For this operation, we need to create an instance of class ‘File’ and pass it to the constructor ofFileInputStream as a parameter. It will store the path of source file

Syntax

FileInputStream nameOfObject = new FileInputStream(objectOfsourceFile);

FileOutputStream Class

It is used to write the content of a file to a specified file. For this operation, we need to create an instance of class ‘File’ and pass it to the constructor of FileOutputStream as a parameter. It will store the path of the destination file.

Syntax

FileOutputStream nameOfObject = new FileOutputStream(objectOfdestinationFile);

Files.copy()

It takes two arguments separated by comma, The first one specifies the source file and the second one specifies the destination file. The destination file must not exist before the copy operation, it will be created implicitly by the compiler based on the instance of destination ‘File’ class. 

Syntax

Files.copy(objectOfSourceFile.toPath(), objectOfDestinationFile.toPath());

Ways to Copy Files in Java

There are two different approaches for performing copy operation

Copy Files using FileInputStream and FileOutputStream

Let’s quickly go through the approach:

Approach

  • Define two instances of class ‘File’. One for source and the other for destination file path.

  • Now, pass these paths to the FileInputStream and FileOutputStream constructors

  • Take a while loop to read and write content of file. The ‘read()’ method will readthe information contained by source file and ‘write()’ method will write the content to destination file.

Example

import java.io.*;
import java.util.*;
public class CopyFile1 {
   public static void main(String[] args) {
      try {
         // to read the path of files
         File flpath1 = new File("D:/Java Programs/file1.txt");
         File flpath2 = new File("D:/Java Programs/file2.txt");
         // passing file path to streams
         FileInputStream inptStrm = new FileInputStream(flpath1);
         FileOutputStream outStrm = new FileOutputStream(flpath2);
         int info = 0;
         // reading the given file1
         while( (info = inptStrm.read()) != -1) {
            outStrm.write(info); // writing to file2
         }
         System.out.print("File1 copied to the given file!!");
      }
      catch(Exception exp) { // for handling exception
         System.out.println("There is an error finding file");
      }
   }
}

Output

File copied to the given file!!

Copy Files using Files.copy() method

Let’s quickly go through the approach:

Approach

  • Define two instances of class ‘File’. One for source and other for destination file path

  • Now, use the in-built method ‘Files.copy()’ method to perform copy operation.

Example

import java.io.*;
import java.nio.file.*;
public class CopyFile2 {
   public static void main(String[] args) {
      try {
         // to read the path of files
         File flpath1 = new File("D:/Java Programs/File1.txt");
         File flpath2 = new File("D:/Java Programs/File2.txt");
         // copying the file1 to file2
         Files.copy(flpath1.toPath(), flpath2.toPath());
         System.out.print("File1 copied to the given file!!");
      }
      catch(Exception exp) { // for handling exception
         System.out.println("There is an error copying the file");
      }
   }
}   

Output

File1 copied to the given file!!

Conclusion

In this article, we have understood several ways to copy files in Java. Each method is quite simple and straightforward however, the best approach will depend on the specific needs of your project. We also discovered the practical implementation of I/O Streams classes and methods through example programs.

Updated on: 20-Jul-2023

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements