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

来源:互联网 发布:社会主义 知乎 编辑:程序博客网 时间:2024/05/16 09:36

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

String(byte[] bytes,String charsetName)

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

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. TheCharsetEncoder 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 0
原创粉丝点击