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

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

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();
	}
}

运行结果:

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

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值