Java Copying file with Apache Commons IO

Apache Commons IO is a library of utilities to assist with developing IO functionality. It contains the FileUtils.copyFile() method to perform copying. FileUtils.copyFile() copies the contents of the specified source file to the specified destination file preserving the file date. The directory holding the destination file is created if it does not exist. If the destination file exists, then this method will overwrite it.
For this example, we need the commons-io artifact:
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

Java Copying file with Apache Commons IO

The example copies a file with Apache Commons' FileUtils.copyFile().
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;

public class CopyFileApacheCommons {
    
    public static void main(String[] args) throws IOException {
        
        File source = new File("src/main/resources/bugs.txt");
        File dest = new File("src/main/resources/bugs2.txt");        
        
        FileUtils.copyFile(source, dest);
    }
}

Comments