Java examples for java.lang:String UTF
Creates a ISO-8859-1 version of an UTF-8 encoded string.
//package com.java2s; public class Main { public static void main(String[] argv) { String utf8String = "java2s.com"; System.out.println(encodeUTF8String(utf8String)); }//from ww w . j av a 2 s . c o m /** * Creates a ISO-8859-1 version of an UTF-8 encoded string. * * @param utf8String * * @return */ public static String encodeUTF8String(String utf8String) { if (utf8String == null) { return null; } if (utf8String.length() == 0) { return ""; } byte[] utf8ByteArray = utf8StringToByteArray(utf8String); return byteArrayToString(utf8ByteArray); } /** Creates a byte array for an UTF-8 encoded string. */ public static byte[] utf8StringToByteArray(String dataString) { if (dataString == null) { return null; } try { return dataString.getBytes("utf-8"); } catch (Exception ex) { } return null; } /** Converts a byte array to a string */ public static String byteArrayToString(byte[] data) { if (data == null) { return null; } char[] result = new char[data.length]; for (int i = 0; i < data.length; i++) { result[i] = (char) (data[i] & 0xFF); } return new String(result); } /** Converts a byte array to a string */ public static String byteArrayToString(byte[] data, int offset, int length) { if (data == null || data.length < offset + length) { return null; } char[] result = new char[length]; for (int i = 0; i < length; i++) { result[i] = (char) (data[offset + i] & 0xFF); } return new String(result); } }