File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Writing a String to a File using FileChannel

dave yendrembam

Joined: Aug 13, 2008
Posts: 1
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"));

The Time taken is slower than using BufferedWriter and FileWriter .

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

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);

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: 692
There was a long thread a few weeks back on this topic.
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

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 classes also use NIO under the covers, so the performance difference for standard operations should be negligible.

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: Writing a String to a File using FileChannel
It's not a secret anymore!