what is difference between writeChars & writeUTF? Thanks, Angela
posted 13 years ago
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.