Java IO Tutorial

How to copy file in Java

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.mkyong.io.howto;

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


public class CopyFile1 {

    public static void main(String[] args) {

        String fromFile = "/home/mkyong/dev/db.debug.conf";
        String toFile = "/home/mkyong/live/db.conf";

        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 doesn'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/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
10 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Cuauh Medina
8 years ago

I’ve got a question, why do you initialize the buffer with 1024 ? does that mean that I can only copy files of 1Mb?

Jeevan Kumar Vishwakarman
11 years ago

Hopefully there is an easier way to do file related operations…
use “Files” class in java itself for easier file operations…
visit

http://docs.oracle.com/javase/tutorial/essential/io/fileOps.html
for more otions

baker
11 years ago

Are you korean ?

Daniel
11 years ago

This example has potential resource leaks! In case of exception streams are still open!

Werner Spurgeon
11 years ago

Nice weblog right here! Additionally your web site loads up very fast! What web host are you using? Can I am getting your associate link to your host? I wish my web site loaded up as fast as yours lol