wood burning stoves 2.0*
The moose likes I/O and Streams and the fly likes Writing a String to a File using FileChannel Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "Writing a String to a File using FileChannel" Watch "Writing a String to a File using FileChannel" New topic
Author

Writing a String to a File using FileChannel

dave yendrembam
Greenhorn

Joined: Aug 13, 2008
Posts: 1
hi
When I started exploring the NIO apis , i found that using FileChannel to write to a file using ByteBuffer is slower compared to normal IO write using BufferedWriter . I even mixed both IO and NIO to write to a file still its slower than using IO BufferedWriter using FileWriter .

//using NIO and IO
String str = "javaranch";
FileChannel fchan = new FileOutputStream("perf-mix.txt").getChannel();
BufferedWriter bf = new BufferedWriter(Channels.newWriter(fchan,"UTF-8"));
bf.write(str);
bf.close();
fchan.close();

The Time taken is slower than using BufferedWriter and FileWriter .

FileWriter fw = new FileWriter("perf-tio.txt", false);
BufferedWriter buf_writer = new BufferedWriter (fw);
buf_writer.write(str);
buf_writer.close();
fw.close();

When i use FileChanne write directly its way too slower than the above two,

FileChannel fc = new FileOutputStream("perf-nio.txt").getChannel();
ByteBuffer bbuf = ByteBuffer.allocate(1024);
bbuf.put(str.getBytes());
bbuf.flip();
fc.write(bbuf);
fc.close();

Am i doing something wrong or The New IO is slower when it comes to writing a String to a file .
Thanks in Advance
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 687
    
    1
There was a long thread a few weeks back on this topic.
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8915
    
    8

The NIO classes are not necessarily faster. What the NIO classes bring to the table is new functionality that would have broken the APIs of the "standard" classes (non-blocking IO comes to mind).
The standard java.io classes also use NIO under the covers, so the performance difference for standard operations should be negligible.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
Don't get me started about those stupid light bulbs.
 
subject: Writing a String to a File using FileChannel