Video in progress
What are the traps of writing a string with `DataOutputStream.writeUTF`?
It writes not plain UTF-8 but "modified UTF-8", and puts a 2-byte length in front. If the encoded string exceeds 65535 bytes you get UTFDataFormatException, and a non-Java reader sees \u0000 and emoji differently.
📖 Answer
In a protocol or file format the writeUTF/readUTF pair looks convenient, but one day you will want to write a big JSON:
out.writeUTF(bigJson); // 70 KB -> UTFDataFormatException: encoded string too long
The length is an unsigned short, so the maximum is 65535 bytes. Since Uzbek ʻ or Cyrillic letters take 2 bytes each, you reach this limit sooner than you would expect by counting characters.
The second problem is the format. In modified UTF-8:
\u0000is not written as a single zero byte but asC0 80;- characters outside the BMP, like emoji, are not a 4-byte UTF-8 sequence: each of the two surrogates takes 3 bytes, 6 bytes in total.
A standard UTF-8 decoder in Go or Python treats these as malformed sequences.
In a format exchanged with an external system, I write the length and plain UTF-8 myself:
byte[] b = text.getBytes(StandardCharsets.UTF_8);
out.writeInt(b.length);
out.write(b);
// reading
int len = in.readInt();
if (len < 0 || len > MAX_LEN) throw new IOException("noto'g'ri uzunlik: " + len);
String s = new String(in.readNBytes(len), StandardCharsets.UTF_8);
Keep writeUTF only where both sides are Java and the strings are definitely small: inside ObjectOutputStream it works exactly like that.
Sign up to mark studied questions and save your progress.