Copy file

This example will show how to copy a file or directory from one location to another using java, guava, apache commons and spring framework. There are many use cases where you need to copy a file from one directory to another. Lets say you are writing an application to upload EAR files that need to be deployed to multiple application servers. After the upload from your browser to a temporary location you will want to copy the file to multiple directories on your network.

In the initial set up below we created a constant for the SOURCE file we want to copy and the DEST we want to copy it to. Be sure when selecting your preferred approach that you check with the associated java docs as each approach has varying behavior

Setup

private static final String SOURCE = "com/levelup/java/io/copy-file.txt";
private static final String DEST = "output/copy-file-2.txt";

private URI sourceFileURI;

@Before
public void setUp() throws URISyntaxException {
    sourceFileURI = this.getClass().getClassLoader().getResource(SOURCE).toURI();
}

File contents

copy a file in java

Straight up Java

Using FileInputStream and FileOutputStream we will move a file from a source location to a destination location. A FileInputStream purpose is for reading streams of raw bytes such as image data and obtains the bytes from a file or file system. In conjunction with FileOutputStream we will loop over the input stream and write the bytes back to the output stream.

Input/Output stream

@Test
public void copy_file_java () throws IOException {

    File sourceFile = new File(sourceFileURI);
    File destinationFile = new File(DEST);
    
    InputStream input = null;
    OutputStream output = null;
    try {
        input = new FileInputStream(sourceFile);
        output = new FileOutputStream(destinationFile);

        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
            output.write(buf, 0, bytesRead);
        }
        
    } finally {
        input.close();
        output.close();
    }
}

Java 7 File I/O

Java 7 NIO introduced a simplified way to copy a file Files utility class. We will specify a Path for the source and destination and then pass them as the first and second parameter into the Files.copy method. The third parameter is a CopyOption giving direction on what behavior to take when making the move. In the snippet below we specified StandardCopyOption.REPLACE_EXISTING as we wanted to replace a file if it already existed. Other options include COPY_ATTRIBUTES and ATOMIC_MOVE.

@Test
public void copy_file_java_nio () throws IOException {
    
    Path sourcePath = Paths.get(sourceFileURI);
    Path destPath = Paths.get(DEST);
    
    java.nio.file.Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
}

Google Guava

Guava Files copy will copy all of the bytes from one file to another and in the event that the TO file exists it will be over written with the from contents.

@Test
public void copy_file_guava () throws IOException {
    
    File sourceFile = new File(sourceFileURI);
    File destinationFile = new File(DEST);
    
    Files.copy(sourceFile, destinationFile);
}

Apache Commons

There are a couple of different ways to copy a file with apache commons both result in copying a file. The first uses FileUtils which copies a file to a new location which copies the contents of the source file to the destination file. If the directory holding the destination file doesn't exist it will be created.

The second is IOUtils which copied the bytes from an InputStream to an OutputStream using an underlying BufferedInputStream. A note in the java doc states that if you are dealing with large streams you should look to use the copyLarge(InputStream, OutputStream) method.

FileUtils

@Test
public void copy_file_apache_fileutils () throws IOException {
    
    File sourceFile = new File(sourceFileURI);
    File destinationFile = new File(DEST);

    FileUtils.copyFile(sourceFile, destinationFile, false);
}

IOUtils

@Test
public void copy_file_apache_ioutils () throws FileNotFoundException, IOException {

    File sourceFile = new File(sourceFileURI);
    File destinationFile = new File(DEST);
    
    IOUtils.copy(new FileInputStream(sourceFile), 
            new FileOutputStream(destinationFile));

}

Spring Framework

Spring framework or spring.io utility class with dealing with files is FileCopyUtils which is primarily used within the framework. The FileCopyUtils.copy like the methods above copies the contents of the given input File to the given output File.

@Test
public void copy_file_spring_framework () throws IOException {

    File sourceFile = new File(sourceFileURI);
    File destinationFile = new File(DEST);
    
    FileCopyUtils.copy(sourceFile, destinationFile);
}