• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Writing a String to a File using FileChannel

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 5008
38
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There was a long thread a few weeks back on this topic.
 
Bartender
Posts: 9626
16
Mac OS X Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Would anybody like some fudge? I made it an hour ago. And it goes well with a tiny ad ...
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic