public final void writeUTF(String str) throws IOException {
    int strlen = str.length();
    int utflen = 0;

    for (int i = 0; i < strlen; i++) {
      int c = str.charAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        utflen++;
      } else if (c > 0x07FF) {
        utflen += 3;
      } else {
        utflen += 2;
      }
    }
    if (utflen > 65535) {
      throw new UTFDataFormatException();
    }

    write((utflen >>> 8) & 0xFF);
    write((utflen) & 0xFF);
    for (int i = 0; i < strlen; i++) {
      int c = str.charAt(i);
      if ((c >= 0x0001) && (c <= 0x007F)) {
        write(c);
      } else if (c > 0x07FF) {
        write(0xE0 | ((c >> 12) & 0x0F));
        write(0x80 | ((c >> 6) & 0x3F));
        write(0x80 | ((c) & 0x3F));
      } else {
        write(0xC0 | ((c >> 6) & 0x1F));
        write(0x80 | ((c) & 0x3F));
      }
    }
  }