try{
s = new String(s.getBytes(), "UTF8");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
改为:
try{
s = new String(s.getBytes(), "GBK");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
看看。
s = new String(s.getBytes(), "UTF8");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
改为:
try{
s = new String(s.getBytes(), "GBK");
byte[] bytes = s.getBytes("UTF8");
System.out.println("length: "+bytes.length);
}catch(java.io.UnsupportedEncodingException uee){
uee.printStackTrace();
}
看看。
static void toUTF8(String s)
{
System.out.println("Source string: "+s);
try
{
byte[] bytes = s.getBytes("ISO-8859-1");
String strReturn = new String(bytes,"UTF-8");
System.out.println(strReturn);
System.out.println( "length: "+strReturn.length() );
}
catch(java.io.UnsupportedEncodingException uee)
{
uee.printStackTrace();
}
}
byte[] bytes = s.getBytes("UTF8");
你多了一个NEW所以才这样,字符转换时不需要的。
长度这样是4。
最后只好自己写了个方法
throws UnsupportedEncodingException
Convert this String into bytes according to the specified character encoding,
storing the result into a new byte array.
这个函数是将字符串按指定的编码方案编码,返回其编码
所以,想知道字符串的UTF8编码的话,可以使用getBytes("UTF8")
byte[] bytes = "中文".getBytes("UTF8");
System.out.println("length: "+bytes.length);
>>length: 6