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 writeChars & writeUTF 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 "writeChars & writeUTF" Watch "writeChars & writeUTF" New topic

writeChars & writeUTF

Angela D'souza
Ranch Hand

Joined: Jan 16, 2002
Posts: 469
what is difference between writeChars & writeUTF?
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
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.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: writeChars & writeUTF
It's not a secret anymore!