This article shows four ways to copy a file in Java.

  1. Files.copy (NIO)
  2. Apache Commons IO
  3. Guava
  4. Plain Java

In Java 7+, the NIO Files.copy is the simplest way to copy a file, because it is a built-in API. Before Java 7, the Apache Commons IO FileUtils.copyFile is a preferable solution because the legacy IO java.io.* has no API to copy.

1. Files.copy (NIO)

1.1 This code snippet uses NIO to copy a file. By default, if the target file exists, the copy fails and throws FileAlreadyExistsException.

  Path fromFile = Paths.get(from);
  Path toFile = Paths.get(to);

  Files.copy(fromFile, toFile);

1.2 The Files.copy takes a varargs argument:

  • StandardCopyOption.REPLACE_EXISTING – If target file exits, replace it.
  • StandardCopyOption.COPY_ATTRIBUTES – Copies the file attributes to the target file.
  import java.nio.file.StandardCopyOption;

  // if target or destination file exists, replace it.
  Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);

  // multiple StandardCopyOption
  CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES,
                LinkOption.NOFOLLOW_LINKS };

  Files.copy(fromFile, toFile, options);

1.3 Below is a complete Java NIO example to copy a file.

CopyFile1.java

package com.favtuts.io.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CopyFile {

    public static void main(String[] args) {
        
        String fromFile = "/home/tvt/workspace/favtuts/sample.csv";
        String toFile = "/home/tvt/workspace/favtuts/backup/sample_bk_20220512.csv";

        try {
            copyFileNIO(fromFile, toFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Copy file is done.");

    }
    
    public static void copyFileNIO(String from, String to) throws IOException {

        Path fromFile = Paths.get(from);
        Path toFile = Paths.get(to);

        // if fromFile does't exist, Files.copy throws NoSuchFileException
        if (Files.notExists(fromFile)) {
            System.out.println("File doesn't exist? " + fromFile);
            return;
        }

        // if toFile folder doesn't exist, Files.copy throws NoSuchFileException
        // if toFile parent folder doesn't exist, create it.
        Path parent = toFile.getParent();
        if (parent!=null) {
            if (Files.notExists(parent)) {
                Files.createDirectories(parent);
            }
        }

        // default - if toFile exist, throws FileAlreadyExistsException
        Files.copy(fromFile, toFile);

        // if toFile exist, replace it.
        // Files.copy(fromFile, toFile, StandardCopyOption.REPLACE_EXISTING);

        // multiple StandardCopyOption
        /*CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES,
                LinkOption.NOFOLLOW_LINKS };

        Files.copy(fromFile, toFile, options);*/
    }
    
}

2. Apache Commons IO

In the old days (before Java 7), the commons-io is the easiest solution to copy a file in Java.

pom.xml

  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
  </dependency>
import org.apache.commons.io.FileUtils;

  public static void copyFileCommonIO(String from, String to)
        throws IOException {

        File fromFile = new File(from);
        File toFile = new File(to);

        FileUtils.copyFile(fromFile, toFile);

  }

3. Google Guava

Many projects start to adopt Guava, and prefer the Guava’s Files.copy, the same name with the Java NIO, make sure you import the correct packages com.google.common.io.Files.

pom.xml

  <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>29.0-jre</version>
  </dependency>
  public static void copyFileGuava(String from, String to) throws IOException {

      File fromFile = new File(from);
      File toFile = new File(to);

      // @Beta?
      com.google.common.io.Files.copy(fromFile, toFile);

  }

The Guava’s Files class is available since version 1.0, no idea why the Files.copy still, has a @Beta annotation on it?

Files.java

package com.google.common.io;

public final class Files {

  //..
  @Beta
  public static void copy(File from, File to) throws IOException {
    checkArgument(!from.equals(to),
      "Source %s and destination %s must be different", from, to);
    asByteSource(from).copyTo(asByteSink(to));
  }

4. Plain Java

This example uses the plain Java InputStream and OutputStream to copy a file.

  public static void copyFilePlainJava(String from, String to) throws IOException {

      InputStream inStream = null;
      OutputStream outStream = null;

      try {

          File fromFile = new File(from);
          File toFile = new File(to);

          inStream = new FileInputStream(fromFile);
          outStream = new FileOutputStream(toFile);

          byte[] buffer = new byte[1024];

          int length;
          while ((length = inStream.read(buffer)) > 0) {
              outStream.write(buffer, 0, length);
              outStream.flush();
          }

      } finally {
          if (inStream != null)
              inStream.close();

          if (outStream != null)
              outStream.close();
      }

  }

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/file

References

Leave a Reply

Your email address will not be published. Required fields are marked *