字符串的编码格式转换
package com.xwl;
import java.io.UnsupportedEncodingException;
/**
* web开发中,tomcat对于传输的字符串都是采用iso-8859-1编码/解码方式。
* 而客户端(浏览器端对于中文都是用gbk或utf-8中文编码/解码方式),所以传到后台都会是乱码的。
* 容器一般都是有处理的,所以中文能正常显示和存储。但有些情况也是会出现乱码的
* @author Administrator
* 解决方式:
*String b = new String(str.getBytes("iso-8859-1","客户端的编码/解码方式")//中文解码方式一般用的是utf-8或者gbk。
*/
public class Testcodingtransition {
public static void main(String[] args) throws UnsupportedEncodingException {
String str = "中国";
System.out.println(str);
String b1 = new String(str.getBytes("gbk"),"gbk");//这里的b1就是采用的gbk的方式解码的 ::::b1不会乱码的
System.out.println(str.getBytes().length);//6
System.out.println(b1);//中国
String b2 = new String(b1.getBytes(),"utf-8");//这里对b1编码后的字节数组重新用utf-8而没有用对应的gbk方式解码。:::::
System.out.println(b2);//中国
String b3 = new String(str.getBytes(),"utf-8");
System.out.println(b3);//中国
String a = "阿里巴巴";
String a1 = new String(a.getBytes("iso-8859-1"),"utf-8");
System.out.println(a1);//出现乱码
String a2 = new String(a.getBytes("iso-8859-1"),"gbk");
System.out.println(a2);//出现乱码
}
}