编码解码问题

package test;
 
 
import java.io.*;
import java.sql.SQLClientInfoException;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.zip.InflaterInputStream;
 
import javax.annotation.processing.FilerException;
import javax.management.RuntimeErrorException;

import privateclass.Filterby_Name;
import privateclass.Filterby_hidden;
import privateclass.Filterby_java;
import privateclass.MyBufferedReader;
import privateclass.Person;
 
public class Main {
 
    private static final String space_operator = " ";
    private static final double pi = Math.PI;
    private static final String LINE_SEPARATOR = System.getProperty("line.separator");
	private static final int SIZE = 1024*1024;


    public static void main(String[] args) throws Exception {

    	String s = "你好";
    	byte buf[] = new byte[1024];
    	//这个默认的是你自己编译器设置的编码
    	buf = s.getBytes();  	
    	String a = new String(buf);
    	printByte(buf);
    	System.out.println(a);
    	
    	//直接用gbk解码
    	buf = s.getBytes("gbk");
    	printByte(buf);
    	String b = new String(buf,"gbk");
    	System.out.println(b);
    	
    	//当我们编码错了我们无法解析出来
    	buf = s.getBytes("iso-8859-1");
    	printByte(buf);
    	String c = new String(buf,"gbk");
    	System.out.println(c);

    	/*
    	 * 当我们解码错了我们还有可能解析出来
    	 * 为什么有可能我们请看下面的两个例子
    	 */
    	//这是重新解码成功的例子
    	buf = s.getBytes("gbk");
    	printByte(buf);
    	String d = new String(buf,"iso-8859-1");
    	System.out.println(d);
    	buf = d.getBytes("iso-8859-1");
    	String e = new String(buf,"gbk");
    	System.out.println(e);
    	//下面是不成功的例子
    	String f = new String(buf,"utf-8");;
    	System.out.println(f);
    	buf = f.getBytes("utf-8");
    	String g = new String(buf,"gbk");
    	System.out.println(g);
    	/*
    	 * 总结原因为什么可能解析成功
    	 * 因为iso-8859-1不认识中文字符
    	 * 并且他是单个字符解析
    	 * 但是Utf-8认识中文字符并且他还支持三个字节为一个汉字
    	 */
    }


	private static void printByte(byte[] buf) {
		for(byte b : buf)
		{
			System.out.print(b + " ");
		}
		System.out.println();
		
	}

}

  

猜你喜欢

转载自www.cnblogs.com/WINDZLY/p/11831683.html