• Programming by 白影를 방문하신 여러분을 환영합니다 :)

FIle Copy 방식

Programming/Java / Flex 白影 2015. 1. 8. 22:20

출처  : http://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:

01private static void copyFileUsingFileStreams(File source, File dest)
02        throws IOException {
03    InputStream input = null;
04    OutputStream output = null;
05    try {
06        input = new FileInputStream(source);
07        output = new FileOutputStream(dest);
08        byte[] buf = new byte[1024];
09        int bytesRead;
10        while ((bytesRead = input.read(buf)) > 0) {
11            output.write(buf, 0, bytesRead);
12        }
13    } finally {
14        input.close();
15        output.close();
16    }
17}

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:

01private static void copyFileUsingFileChannels(File source, File dest)
02        throws IOException {
03    FileChannel inputChannel = null;
04    FileChannel outputChannel = null;
05    try {
06        inputChannel = new FileInputStream(source).getChannel();
07        outputChannel = new FileOutputStream(dest).getChannel();
08        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
09    } finally {
10        inputChannel.close();
11        outputChannel.close();
12    }
13}

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:

1private static void copyFileUsingApacheCommonsIO(File source, File dest)
2        throws IOException {
3    FileUtils.copyFile(source, dest);
4}

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:

1private static void copyFileUsingJava7Files(File source, File dest)
2        throws IOException {
3    Files.copy(source.toPath(), dest.toPath());
4}