String和bytes的编码转换

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * @author 作者 E-mail:
 * @version 创建时间:2015-10-9 上午10:06:42 类说明
 */
public class Test
{
    public static void main(String[] args) throws UnsupportedEncodingException
    {  
        System.out.println(System.getProperty("sun.jnu.encoding"));
        
        System.out.println(Charset.defaultCharset().name());
        
        byte bytes[] = new byte[] { 50, 0, -1, 28, -24 };
        
        String string = new String(bytes);

        //Java中一个char是两个字节 gbk也是采用两个字节编码一个汉字
        System.out.println("string.length = " + string.length() );
        
        byte[] ret = string.getBytes();
        
        for (int i = 0; i < ret.length; i++)

            System.out.print(ret[i] + " ");
        
        System.out.println();
        for(int j=0;j<string.length();j++)
        {
            System.out.print(string.charAt(j) + " ");
        }
    }
}

 上述代码的输出结果:

GBK
GBK
string.length = 4
50 0 63 63 
2 

 

这样输出结果的原因?回来分析下

posted @ 2015-10-09 13:30  无心流泪  阅读(1848)  评论(0)    收藏  举报