Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Writing a String to a File using FileChannel

 
dave yendrembam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 733
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was a long thread a few weeks back on this topic.
 
Joe Ess
Bartender
Pie
Posts: 9264
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic