Note that there are some explanatory texts on larger screens.

plurals
  1. POJava NIO FileChannel versus FileOutputstream performance / usefulness
    text
    copied!<p>I am trying to figure out if there is any difference in performance (or advantages) when we use nio <code>FileChannel</code> versus normal <code>FileInputStream/FileOuputStream</code> to read and write files to filesystem. I observed that on my machine both perform at the same level, also many times the <code>FileChannel</code> way is slower. Can I please know more details comparing these two methods. Here is the code I used, the file that I am testing with is around <code>350MB</code>. Is it a good option to use NIO based classes for File I/O, if I am not looking at random access or other such advanced features?</p> <pre><code>package trialjavaprograms; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class JavaNIOTest { public static void main(String[] args) throws Exception { useNormalIO(); useFileChannel(); } private static void useNormalIO() throws Exception { File file = new File("/home/developer/test.iso"); File oFile = new File("/home/developer/test2"); long time1 = System.currentTimeMillis(); InputStream is = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(oFile); byte[] buf = new byte[64 * 1024]; int len = 0; while((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); fos.close(); is.close(); long time2 = System.currentTimeMillis(); System.out.println("Time taken: "+(time2-time1)+" ms"); } private static void useFileChannel() throws Exception { File file = new File("/home/developer/test.iso"); File oFile = new File("/home/developer/test2"); long time1 = System.currentTimeMillis(); FileInputStream is = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(oFile); FileChannel f = is.getChannel(); FileChannel f2 = fos.getChannel(); ByteBuffer buf = ByteBuffer.allocateDirect(64 * 1024); long len = 0; while((len = f.read(buf)) != -1) { buf.flip(); f2.write(buf); buf.clear(); } f2.close(); f.close(); long time2 = System.currentTimeMillis(); System.out.println("Time taken: "+(time2-time1)+" ms"); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload