Java Charset, getBytes()

package com.cg.test;

import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.binary.Hex;

public class HexString {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
	
	String s="1a国";
	System.out.println("原始字符串:"+s);
	
	System.out.println(s.getBytes("ASCII").length);
	String sEncoded = Hex.encodeHexString(s.getBytes("ASCII"));
	System.out.println("ASCII: "+sEncoded);
	
	sEncoded = Hex.encodeHexString(s.getBytes("GBK"));
	System.out.println("GBK: "+sEncoded);

	System.out.println("Default charset: "+Charset.defaultCharset().name());
	sEncoded = Hex.encodeHexString(s.getBytes());
	System.out.println("Default: "+sEncoded);
	//output:3161e59bbd

	//BOM: Byte Order Mark 字节序标记
	sEncoded = Hex.encodeHexString(s.getBytes("UNICODE"));
	System.out.println("UNICODE: "+sEncoded);
//	output: feff0031006156fd
	
	sEncoded = Hex.encodeHexString(s.getBytes("UTF-16"));
	System.out.println("UTF-16: "+sEncoded);
	//output: feff0031006156fd
	
	sEncoded = Hex.encodeHexString(s.getBytes("x-UTF-16LE-BOM"));
	System.out.println("x-UTF-16LE-BOM: "+sEncoded);
	//output: fffe31006100fd56
	

	sEncoded = Hex.encodeHexString(s.getBytes("UTF-16BE"));
	System.out.println("UTF-16BE: "+sEncoded);
	//output: 0031006156fd
	
	sEncoded = Hex.encodeHexString(s.getBytes("UTF-16LE"));
	System.out.println("UTF-16LE: "+sEncoded);
	//output: 31006100fd56
	
	System.out.println("返回当前的 JVM 中可以使用的字符集");
	 Map m=Charset.availableCharsets();
         Set set=m.keySet();
         Iterator it=set.iterator();
         while(it.hasNext()){
                System.out.println(it.next());
         }
         
    }

}

  

 

posted @ 2012-07-06 17:05  庚武  Views(932)  Comments(0Edit  收藏  举报