Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

writeChars & writeUTF

 
Angela D'souza
Ranch Hand
Posts: 469
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is difference between writeChars & writeUTF?
Thanks,
Angela
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They are described in detail in the API for DataOutput, an interface which RandomAccessFile implements. Basically, writeChars() uses Unicode values, writing two bytes per character. While writeUTF() uses a slightly-modified version of UTF-8, which uses 1 to 3 bytes per character. Also, writeUTF() writes two bytes at the beginning which identify the number of characters which will be in the UTF-8 representation, so the readUTF() method will know when to stop. The writeChars() method does not do this, and also does not write a delimiter (like 0) at the end of the String - so I'm not sure what it's really useful for. The DataInput interface does not define a readChars() method, because writeChars() does not provide enough information to know reliably where the string should terminate. There are ways to fix this, but in general it's too much trouble - I'd usually just ignore writeChars() and use writeUTF() instead, whenever I have String data to write to a binary file.
Of course, if you're writing a text file rather than a binary file, you probably shouldn't be using any of the DataOutput / DataInput methods anyway. They have too many methods which generate unprintable chars if you don't know exactly what you're doing. Use Readers and Writers; they're much better.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic