File copy example

In this post under Apache Commons IO, I will explain with example how to copy a file.

Apache provides “IOUtils” static class which has static method “copy”.

We can use this “copy” method to copy files.

Below is the complete main code for your reference.

Main class

package ioutils;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Example3 {
    public static void main(String[] args) throws IOException {
        File inputFile = new File("Quotes.txt");
        File outputFile = new File("QuotesCopy.txt");
        try(FileReader fileReader = new FileReader(inputFile);
            FileWriter fileWriter = new FileWriter(outputFile)) {
            IOUtils.copy(fileReader, fileWriter);
        }
    }
}

In the above code, I create two instances of “File” class one for source file and another for destination file.

In the try-with-resource block, we create reader and writer instances “fileReader” and “fileWriter”.

At line 16, I call “copy” method and pass the reader and writer instances as arguments.

There are several overloaded version of “copy” method which takes different types of parameter.

In this way we can copy a file.

Leave a comment