10.7 java

1.关键技术点

*String的getBytes方法用于按指定编码获取字符串的字节数组

*String的"String(bytes[] bs, String charset)"构造方法用于把字节数组按指定的格式组合成一个字符串对象

2.更改字符串编码步骤

*调用String的getBytes方法对字符串进行解码,得到字符串的字节数组

*根据字节数组和新的字符编码构造一个新的String对象,得到的就是按照新的字符编码生成的字符串

public class CharetDemo1 {
 public static void main(String[] args) throw Unsupported Encoding
  throws Unsupported Encoding
   Exception{
    String str = "吴正云";
    String utf8 = changeCharSet(str,"utf-8");
    String gbk = changeCharSet(str, "gbk");
    String gb2312 = changeCharSet(str, "gb2312");
    String iso = changeCharSet(str, "ISO-8859-1");
    System.out.println("utf8:" + utf8);
    System.out.println("gbk:" + gbk);
    System.out.println("gb2312:" + gb2312);
    System.out.println("ISO-8859-1:" + iso);
  }
  public static String changeCharSet(String old, String charSet) throws
   UnsupportedEncodingException {
   byte[] buf = old.getBytes();
   String str = new String(buf, charSet);
   return str;
  }
 }

 

posted @ 2020-10-07 17:27  鯨落  阅读(101)  评论(0编辑  收藏  举报