Different Ways to Copy Files in Java

04 Mar, 2022
There are mainly 3 ways to copy files using java language. They are as given below:
Using File Stream (Naive method)Using FileChannel ClassUsing Files class.
Using File Stream (Naive method)
Using FileChannel Class
Using Files class.
Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes.
Method 1: Using File Stream (Naive method)
This is a naive method where we are using a file input stream to get input characters from the first file and a file output stream to write output characters to another file. This is just like seeing one file and writing onto another.
Example:
Java
// Java Program to Copy file using File Stream // Importing input output classesimport java.io.*; // Main Classpublic class GFG {     // Main driver method    public static void main(String[] args)        throws IOException    {         // Creating two stream        // one input and other output        FileInputStream fis = null;        FileOutputStream fos = null;         // Try block to check for exceptions        try {             // Initializing both the streams with            // respective file directory on local machine             // Custom directory path on local machine            fis = new FileInputStream(                "C:\\Users\\Dipak\\Desktop\\input.txt");             // Custom directory path on local machine            fos = new FileOutputStream(                "C:\\Users\\Dipak\\Desktop\\output.txt");             int c;             // Condition check            // Reading the input file till there is input            // present            while ((c = fis.read()) != -1) {                 // Writing to output file of the specified                // directory                fos.write(c);            }             // By now writing to the file has ended, so             // Display message on the console            System.out.println(                "copied the file successfully");        }         // Optional finally keyword but is good practice to        // empty the occupied space is recommended whenever        // closing files,connections,streams        finally {             // Closing the streams             if (fis != null) {                 // Closing the fileInputStream                fis.close();            }            if (fos != null) {                 // Closing the fileOutputStream                fos.close();            }        }    }}
 Output:  
copied the file successfully 
 
For the above program, we require one input.txt and one output.txt file. Initially, both the text files look like this 
 
After successful execution of the program, 
 
Method 2: Using FileChannel Class 
This is a class present in java.nio, channels package and is used to write, modify, read files. The objects of this class create a seekable file channel through which all these activities are performed. This class basically provides two methods named as follows:
transferFrom(ReadableByteChannel src, long position, long count): Transfers bytes to the channel which calls this method from the src channel. This is called by destination channel. The position is the place of a pointer from where the copy actions are to be started. Count specifies the size of the file which is nearly equal to the amount of content it contains.
transferTo(long position, long count, WritableByteChannel target): Transfers bytes from the source or method calling channel to the destination channel of the file. This method is mainly called using the source channel and Count mentions the size of the source file and position from where the copy is to be made
 
Hence, we can use any one of the two methods to transfer files data and copy them. 
Example:
Java
// Java Program to Copy Files Using FileChannel Class // Importing java.nio package for network linking// Importing input output classesimport java.io.*;import java.nio.channels.FileChannel; // Main Classpublic class GFG {     // Main driver method    public static void main(String[] args)        throws IOException    {         // Creating two channels one input and other output        // by creating two objects of FileChannel Class        FileChannel src            = new FileInputStream(                  "C:\\Users\\Dipak\\Desktop\\input.txt")                  .getChannel();        FileChannel dest            = new FileOutputStream(                  "C:\\Users\\Dipak\\Desktop\\output.txt")                  .getChannel();         // Try block to check for exceptions        try {             // Transferring files in one go from source to            // destination using transferFrom() method            dest.transferFrom(src, 0, src.size());            // we can also use transferTo            // src.transferTo(0,src.size(),dest);        }         // finally keyword is good practice to save space in        // memory by closing files, connections, streams        finally {             // Closing the channels this makes the space            // free             // Closing the source channel            src.close();             // Closing the destination channel            dest.close();        }    }}
Output: 
For the above program, we require one input.txt and one output.txt file. Initially, both the text files look like this
 
 
After successful execution of the program,
 
 
Method 3: Using Files Class 
This is a class present in java.nio.File package. This class provides 3 methods to copy the files which are as follows: 
copy(InputStream in, Path target): Copies all bytes of data from the input file stream to the output path of the output file. It cannot be used to make a copy of a specified part in a source file. Here we are not required to create an output file. It is automatically created during the execution of the code.
copy(Path source, OutputStream out): Copies all bytes from the file specified in the path source to the output stream of the output file.
copy(Path source, Path target): Copies files using the path of both source and destination files. No need to create the output file here also.
 
Example:
Java
import java.nio.file.Files;import java.io.*;// save the file named as GFG.javapublic class GFG{       // main method    public static void main(String[] args) throws IOException{               // creating two channels        // one input and other output           File src = new File("C:\\Users\\Dipak\\Desktop\\input.txt");        File dest = new File("C:\\Users\\Dipak\\Desktop\\output.txt");                     // using copy(InputStream,Path Target); method        Files.copy(src.toPath(), dest.toPath());               // here we are not required to have an        // output file at the specified target.        // same way we can use other method also.                 }}
Output:
For the above program, we require one input.txt and one output.txt file. Initially, both the text files look like this
After successful execution of the program,
Note: Out of all these methods the stream one is fast in process but if someone wants to be technical and more advanced than they can opt for the other two methods. Also the FileChannel method provides us a lot of options to control the part of the file to be copied and to specify its size.
simmytarika5
simranarora5sos
gulshankumarar231
sweetyty
Java-Files
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.