skip to main | skip to sidebar

Thursday, November 17, 2011

File Copy Using Java NIO

I wanted to post this small piece of code for those who are looking for it. Copying file contents using Streams is old way of doing, Java New IO is the way to go; using Java NIO is better in terms of performance.
Following is the code to do file copy using Java NIO.

public static void copyFile(File src, File dest) throws IOException {
    if (!src.exists()) {
        // either return quietly OR throw an exception
        return;
    }
    if (!dest.exists()) {
        dest.createNewFile();
    } 

    FileChannel source = new FileInputStream(src).getChannel();
    try {
        FileChannel destination = new FileOutputStream(dest).getChannel();
        try {
            source.transferTo(0, source.size(), destination);
            // destination.transferFrom(source, 0, source.size());
        } finally {
            if (destination != null) {
                destination.close();
            }
        }
    } finally {
        if (source != null) {
            source.close();
        }
    }
} 

By using NIO classes, we don’t need to create those byte buffers, loop through and copy in chunks, etc. NIO code is clean and simple, below line of code is the one responsible for copying file content.

source.transferTo(0, source.size(), destination); 

Quite simple isn’t it. It gets even simpler in Java7, all we need is one line of code as given below

Files.copy(src, dest);

// OR

Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

In the above line of code ‘src’ and ‘dest’ are not instances of java.io.File class, but they are of type "java.nio.file.Path". You can get Path object instance either by calling "toPath()" method on "java.iolFile" class object, OR creating one by calling the "getPath()" method on "java.nio.file.FileSystem" object.

FileSystems.getDefault().getPath("logs", "access.log");

The above line of code will give you an instance of ‘java.nio.file.Path’, which points to a file ‘access.log’ available in ‘logs’ directory, path is relative to current directory ["./logs/access.log"]. You can find more information @ http://today.java.net/pub/a/today/2008/07/03/jsr-203-new-file-apis.html
Read more »»