Skip to main content

Posts

Showing posts from November, 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();