11

What's the difference between writeUTF and writeChars? (methods of ObjectOutputStream) Further I have not found the corresponding readChars in ObjectInputStream.

Mithical
  • 603
  • 1
  • 17
  • 28
Indeed ItIs
  • 257
  • 3
  • 10

2 Answers2

14

writeUTF writes text in UTF-8 format encoding preceeded with text length, so readUTF knows how many characters to read from stream.

writeChars writes text as a sequence of 2-bytes chars with no length. To read it, we should use readChar method and we need to know how many chars were written.

bvdb
  • 22,839
  • 10
  • 110
  • 123
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
3

writeChars() uses Unicode values

Writes every character in the string s, to the output stream, in order, two bytes per character. If s is null, a NullPointerException is thrown. If s.length is zero, then no characters are written. Otherwise, the character s[0] is written first, then s1, and so on; the last character written is s[s.length-1]. For each character, two bytes are actually written, high-order byte first, in exactly the manner of the writeChar method.

writeUTF() uses a slightly-modified version of UTF-8

Writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s. If s is null, a NullPointerException is thrown. Each character in the string s is converted to a group of one, two, or three bytes, depending on the value of the character.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331