HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Copy File

Java Copy File

Copying a file from one place to another in Java is a common task which we need to do in the applications. In this Java tutorial, we will see different ways to copy a file in Java.

In all given examples, we will be copying the content of testoriginal.txt to an another file testcopied.txt. The name and the location of the files can be replaced in any of the examples.

Copying is not an atomic operation – in the case of an I/O error, power loss, process termination, or other problems, the copying operation is not complete. If we need to guard against those conditions, we should employ other file-level synchronization.

Copying File with Files.copy()

The Files class is in java.nio.file package. It provides the static methods that operate on files, directories, or other types of files.

Use the StandardCopyOption enum which defines how the copy should be done.

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

void fileCopyUsingNIOFilesClass() throws IOException 
{
	Path source = Paths.get("c:/temp/testoriginal.txt");
	Path destination = Paths.get("c:/temp/testcopied.txt");

	Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
}

Java Copy File using FileChannel.transferTo()

If you are fond of FileChannel class for their brilliant performance, use this method. The key advantage here is that the JVM uses the OS’s access to DMA (Direct Memory Access) if present.

Using this technique, the data goes straight to/from disc to the bus, and then to the destination… bypassing any circuit through RAM or the CPU.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

private static void fileCopyUsingNIOChannelClass() throws IOException 
{
	File fileToCopy = new File("c:/temp/testoriginal.txt");
	FileInputStream inputStream = new FileInputStream(fileToCopy);
	FileChannel inChannel = inputStream.getChannel();

	File newFile = new File("c:/temp/testcopied.txt");
	FileOutputStream outputStream = new FileOutputStream(newFile);
	FileChannel outChannel = outputStream.getChannel();

	inChannel.transferTo(0, fileToCopy.length(), outChannel);

	inputStream.close();
	outputStream.close();
}

Java Copy File using Apache Commons IO

To use Apache Commons IO, we will need to download the commons-io dependency and include in the project.

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

Use one of the following classes for copying one file to another.

  • FileUtils – Internally it uses the java.nio.file.Files class so it is equivalent to use the java.nio.file.Files.copy() function.
  • IOUtils – It copies bytes from a large (over 2GB) InputStream to an OutputStream. This method uses the provided buffer, so there is no need to use a BufferedInputStream.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

void fileCopyUsingApacheCommons() throws IOException 
{
	File fileToCopy = new File("c:/temp/testoriginal.txt");
	File newFile = new File("c:/temp/testcopied.txt");

	FileUtils.copyFile(fileToCopy, newFile);

	// OR

	IOUtils.copy(new FileInputStream(fileToCopy), new FileOutputStream(newFile));
}

Java Copy File using Guava

To use Guava, we will need to download the com.google.guava dependency and include in the project.

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>28.2-jre</version>
</dependency>

The Files class provides utility methods for working with files. The Files.copy() method copies all the bytes from one file to another.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.google.common.io.Files;

void fileCopyUsingGuava() throws IOException 
{
	File fileToCopy = new File("c:/temp/testoriginal.txt");
	File newFile = new File("c:/temp/testcopied.txt");

	Files.copy(fileToCopy, newFile);
}

After Java 7, there have not been any major improvements in the Java IO package. So for any later Java release (Java 8 to Java 14), we have to reply on above-listed techniques.

Happy Learning !!

Sourcecode Download

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. firstpostcommenter

    April 26, 2017

    I am using Java8. Which method is the best one?

    • Lokesh Gupta

      August 10, 2020

      For small files, I will go with java.nio.file.Files.copy(). For larger files, I will try first the FileChannel.transferTo() API.

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)