Skip to content

Instantly share code, notes, and snippets.

@ezhov-da
Last active March 10, 2019 12:15
Show Gist options
  • Save ezhov-da/eb8b578069ba077942ea2f69d9d7a13e to your computer and use it in GitHub Desktop.
Save ezhov-da/eb8b578069ba077942ea2f69d9d7a13e to your computer and use it in GitHub Desktop.
copy file
[https://examples.javacodegeeks.com/core-java/io/file/4-ways-to-copy-file-in-java/]
1. Copy File Using FileStreams
This is the most classic way to copy the content of a file to another. You simply read a number of bytes from File A using FileInputStream and write them to File B using FileOutputStream.
Here is the code of the first method:
private static void copyFileUsingFileStreams(File source, File dest)
throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
As you can see we perform several read and write operations on big chucks of data, so this ought to be a less efficient compared to the next methods we will see.
2. Copy File using java.nio.channels.FileChannel
Java NIO includes a transferFrom method that according to the documentation is supposed to do faster copying operations than FileStreams.
Here is the code of the second method:
private static void copyFileUsingFileChannels(File source, File dest)
throws IOException {
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputChannel = new FileInputStream(source).getChannel();
outputChannel = new FileOutputStream(dest).getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
inputChannel.close();
outputChannel.close();
}
}
3. Copy File using Apache Commons IO
Apache Commons IO offers a copyFile(File srcFile, File destFile) method in its FileUtils class that can be used to copy a file to another. It’s very convenient to work with Apache Commons FileUtils class when you already using it to your project. Basically, this class uses Java NIO FileChannel internally.
Here is the code of the third method:
private static void copyFileUsingApacheCommonsIO(File source, File dest)
throws IOException {
FileUtils.copyFile(source, dest);
}
4. Copy File using Java 7 Files class
If you have some experience in Java 7 you will probably know that you can use the copy mehtod of the class Files in order to copy a file to another.
Here is the code of the fourth method:
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment