Skip to main content

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

Comments

Popular posts from this blog

Hosting Multiple Domains In Tomcat

Tomcat allows us to host multiple domains in one instance, using multiple 'Host' tags. In this article I will explain how to do it on Tomcat. This is very simple configuration using 'Host' tags in your server.xml. A novice can also understand this configuration very easily.
Before going into the details of the configuration first lets have a look at the 'Host' tag, 'Context' tag and 'Alias' tags first.
<Host name="domain1" appBase="[application base]" autoDeploy="[true/false]" unpackWARs="[true/false]"> <Alias>...</Alias> <Context path="" docBase="" reloadable="[true/false]"/> </Host> First lets have a look at 'Alias' tag. This tag is used to provide aliases for your actual domain. For example you have a domain called 'domain1.com', and you want to run the same application for 'www.domain1.com' also…

File Uploading Using Servlets, JSP and Commons File Upload API

I’ve seen many developers who are at the early stages of their career have problems with this topic and seen many posts in forums asking how to do it – File Uploading using Servlets, JSP!; this article will provide an example using Commons File Upload API. I tried to make the example as simple as possible, hope it helps those early birds. Example uses JSP to provide the pages with form where user can select the file to upload with other form fields, Commons File Upload API to process submitted form and read form fields separately, and Servlets as middle layer between JSP and Commons File Upload API, example also has ANT build script to generate the distributables. All the code can be downloaded, links to these resources are provided at the end of this post, lets get on with the example then.
The flow in this example is as depicted in the following picture.
As you can see, user selects the file to upload and provides normal form data as well, using "index.jsp" and submits th…

About Rakesh.A

As the URL and other parts of this blog says, I am Rakesh.A, a techie form Hyderabad, India. I am working for coMakeIT, Hyderabad as a Sr. Software Engineer, that's about me in short.
How I ended up in this profession? - Well when I was doing my schooling I never thought I'll be into this profession, infact I wasn't that interested in Information Technology/Software Development, so never concentrated on it even after my parents stressed to get into it. After couple of years, I saw myself doing the same. And now I can't even think of myself being in a different profession. Anything I can do with whole heart, that's only PROGRAMMING/DEVELOPMENT.
As every student who got into this profession, I felt my FIRST LOVE with 'C language', and I love coding in C. Then I started learning Object Oriented Programming and got attracted to 'C++ language', but it was 'JAVA' in which I saw my soul mate. That's it I got married to it and settled. I've…