Apache FileUtils copying file



This example demonstrates how to copy files using the Apache commons library.

The example copies a file in the same directory and compares its contents. Then it creates a new directory and copies a file to this new directory.

Maven Dependency

Let's add maven dependency before creating these examples:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

Apache FileUtils copying file

The example copies a file in the same directory and compares its contents. Then it creates a new directory and copies a file to this new directory.


import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class CopyFileExample {
    
    public static void main(String[] args) throws IOException {
        
        File myfile1 = new File("src/main/resources/myfile.txt");
        File myfile2 = new File("src/main/resources/myfile2.txt");
        
        FileUtils.copyFile(myfile1, myfile2);
        
        if (FileUtils.contentEquals(myfile1, myfile2)) {
            
            System.out.println("The files have equal content");
        } else {
            
            System.out.println("The files do not have equal content");
        }
        
        File docs = new File("src/main/resources/docs");
        FileUtils.forceMkdir(docs);
        
        FileUtils.copyFileToDirectory(myfile2, docs);
    }
}

Files can be copied with the FileUtils.copyFile() and FileUtils.copyFileToDirectory() methods. To compare the file contents, we can use the FileUtils.contentEquals() method.

Comments