UnsafeByteArrayOutputStream extends Output implements ExtendedDataOutput { @Override public void writeUTF(String s) throws IOException { int strlen = s.length(); int utflen = 0; int c; for (int i = 0; i < strlen; i++) { c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { utflen++; } else if (c > 0x07FF) { utflen += 3; } else { utflen += 2; } } if (utflen > 65535) { throw new UTFDataFormatException( "encoded string too long: " + utflen + " bytes"); } require(utflen + SIZE_OF_SHORT); writeShort(utflen); int i = 0; for (i = 0; i < strlen; i++) { c = s.charAt(i); if (!((c >= 0x0001) && (c <= 0x007F))) { break; } buffer[position++] = (byte) c; } for (; i < strlen; i++) { c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { buffer[position++] = (byte) c; } else if (c > 0x07FF) { buffer[position++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); buffer[position++] = (byte) (0x80 | ((c >> 6) & 0x3F)); buffer[position++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } else { buffer[position++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); buffer[position++] = (byte) (0x80 | ((c >> 0) & 0x3F)); } } } UnsafeByteArrayOutputStream();  UnsafeByteArrayOutputStream(int size);  UnsafeByteArrayOutputStream(byte[] buf);  UnsafeByteArrayOutputStream(byte[] buf, int pos); @Override byte[] getByteArray(); @Override byte[] toByteArray(); @Override byte[] toByteArray(int offset, int length); @Override void reset(); @Override int getPos(); @Override void write(int b); @Override void write(byte[] b); @Override void write(byte[] b, int off, int len); @Override void writeBoolean(boolean v); @Override void writeByte(int v); @Override void writeShort(int v); @Override void writeChar(int v); @Override void writeChar(char v); @Override void writeInt(int v); @Override void ensureWritable(int minSize); @Override void skipBytes(int bytesToSkip); @Override void writeInt(int pos, int value); @Override void writeLong(long v); @Override void writeFloat(float v); @Override void writeDouble(double v); @Override void writeBytes(String s); @Override void writeChars(String s); @Override void writeUTF(String s);  }
@Test public void testWriteUTF() throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20; i++) { sb.append("\u06ea"); } String s = sb.toString(); assertEquals(s, writeAndReadUTF(s)); }