牛骨文教育服务平台(让学习变的简单)
博文笔记

关于java String类的getBytes(String charsetName)和String(byte[] bytes, String charsetName)

创建时间:2013-12-10 投稿人: 浏览次数:8287

首先看官方文档上对这两个方法的解释:

String(byte[] bytes, String charsetName)

Constructs a new String by decoding the specified array of bytes using the specified charset. ------------------------------

public byte[] getBytes(String charsetName)
                throws UnsupportedEncodingException
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.

The behavior of this method when this string cannot be encoded in the given charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

如果没有一个范例作为参考,看完了上面的说明可能依然是云里雾里不知所以,下面这个例子便于理解上面两个方法。

代码:

public class Test {
	
	public Test(){
		try{
	      String str=new String("我爱天安门");
	      byte by_gbk[]=str.getBytes("GBK");
	      String str_gbk=new String(by_gbk,"GBK");
	      System.out.println("str_gbk:"+str_gbk);
	      String str_utf8=new String(by_gbk,"UTF-8");
	      System.out.println("str_utf8:"+str_utf8);
	      System.out.println("----------------------");
	      byte by_utf8[]=str.getBytes("UTF-8");
	      String str2_gbk=new String(by_utf8,"GBK");
	      System.out.println("str2_gbk:"+str2_gbk);
	      String str2_utf8=new String(by_utf8,"UTF-8");
	      System.out.println("str2_utf8:"+str2_utf8);
	      
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args){
		new Test();
	}
}

运行结果:

(------仅作参考------)

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。