How to copy file in Java
This article shows four ways to copy a file in Java.
Files.copy
(NIO)- Apache Commons IO
- Guava
- 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.
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.
<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
.
<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?
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
I’ve got a question, why do you initialize the buffer with 1024 ? does that mean that I can only copy files of 1Mb?
buffer, copy 1024 bytes at a time.
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
Yes, Java NIO
Files.copy
is the preferable solution.Are you korean ?
No.
This example has potential resource leaks! In case of exception streams are still open!
Thanks. The article is updated to close the resource at the finally step.
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
This comment was 8 years ago, during that time, I think the “liquidweb” hosted this website, and they have excellent support. The speed is a file cache served by CDN Cloudflare.