Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

writing a string array to a file using FileChannel  RSS feed

 
Stewart Grossman
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For FileChannel, would this work:
1) convert the String Array into byte arrays
2) wrap the byte arrays into bytebuffers
3) create a bytebuffer array from the bytebuffers
4) use FileChannel's write(ByteBuffer[], int offset, int length) method to write the data to the file
Note: I want to overwrite the existing data in the file. Will write() do this or does it append instead? I'm not sure from the documentation.
Or should I just use RandomAccessFile's writeBytes(String s) method? What's the upside to using FileChannel instead of using RandomAccessFile? Seems more difficult.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According the API
Bytes are written starting at this channel's current file position unless the channel is in append mode, in which case the position is first advanced to the end of the file.

Not sure what the advantages are, other than my own bias against using RandomAccessFile (I just don't like it for some reason).
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
FileChannel can be much faster then RandomAccessFile. If the file is very large, or if performance is an issue for other reasons, FileChannel kicks butt. And if you're pursuing improved performance, you should probably avoid creating new byte arrays - use ByteBuffer and CharBuffer instead. I'd probably create a CharBuffer with enough space to work with, put all the Stirngs into the CharBuffer, then use a CharsetEncoder to convert that to a ByteBuffer, then write the ByteBuffer contents to the FileChannel. You can also use Charset's encode(String) method for convenience; though you could probably get better effieicenct bypassing this with other methods as previously described. I'm thinking each separate encode(String) call has more overhead than if you do a bunch of them in bulk. But this level of optimization is quite possibly unnecessary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!