public static final String utf8_decode(byte[] utf8_bytes) throws java.io.UTFDataFormatException {<br /> return utf8_decode(utf8_bytes, 0, utf8_bytes.length);<br /> }</p><p> public static final String utf8_decode(byte[] utf8_bytes, int start, int len) throws java.io.UTFDataFormatException {<br /> if (utf8_bytes == null)<br /> return null;<br /> int end = start + len;<br /> char[] unicode_chars = new char[len];<br /> int i, counter = 0;<br /> try {<br /> for (i = start; i < end; i++) {<br /> byte b = utf8_bytes[i];<br /> if ((b >> 7) == 0) { // read one byte<br /> unicode_chars[counter++] = (char) (b);<br /> } else if ((b >> 5) == (byte) 0xfe) { // read two bytes<br /> unicode_chars[counter] = (char) ((char) (b & 0x1f) << 6);<br /> unicode_chars[counter++] += utf8_bytes[++i] & 0x3f;<br /> } else if ((b >> 4) == (byte) 0xfe) { // read three bytes<br /> unicode_chars[counter] = (char) ((char) (b & 0xf) << 12);<br /> unicode_chars[counter] += (char) ((char) (utf8_bytes[++i] & 0x3f) << 6);<br /> unicode_chars[counter++] += utf8_bytes[++i] & 0x3f;<br /> }<br /> }<br /> return new String(unicode_chars, 0, counter);<br /> } catch (Exception ex) {<br /> throw new java.io.UTFDataFormatException();<br /> }<br /> }</p><p> public static final byte[] utf8_encode(String src) {<br /> if (src == null)<br /> return null;<br /> /** copy chars into array */<br /> int len = src.length();<br /> char[] chars = src.toCharArray();<br /> byte[] bytes = new byte[len * 3];<br /> int counter = 0;<br /> char c;<br /> for (int n = 0; n < len; n++) {<br /> c = chars[n];<br /> if (c < 128)<br /> bytes[counter++] = (byte) c;<br /> else if ((c > 127) && (c < 2048)) {<br /> bytes[counter++] = (byte) ((c >> 6) | 192);<br /> bytes[counter++] = (byte) ((c & 63) | 128);<br /> } else {<br /> bytes[counter++] = (byte) ((c >> 12) | 224);<br /> bytes[counter++] = (byte) (((c >> 6) & 63) | 128);<br /> bytes[counter++] = (byte) ((c & 63) | 128);<br /> }<br /> }<br /> byte[] result = new byte[counter];<br /> System.arraycopy(bytes, 0, result, 0, counter);<br /> bytes = null;<br /> chars = null;<br /> return result;<br /> }