java基礎--->字符編碼

轉換流的字符編碼

一、概述

編碼表的由來:
1.計算機智能識別(1,0)這樣的二進制數據
2.爲了方便應用計算機,讓他識別各個國家的文字,就將各個國家的文字用數字來表示,形成一對一的對應關係,從而形成了一張表
3.這就是編碼表

二、常見的編碼表:
1.ASCII:美國標準信息交換碼
用一個字節中的7位就可以表示
2.ISO8859-1:拉丁碼錶(歐洲碼錶)
用一個字節的8位表示。
3.GB2312:中文碼錶
兼容ASCII碼錶,中文的兩個8位高位都是1
4.GBK:升級版的中文碼錶
融合了更多的中文文字字符
5.Unicode:國際標準碼錶
所有文字都由兩個8位來表示(比較浪費空間),融合了多種文字,Java語言使用的是unicode(char)
6.UTF-8:unicode轉換格式(全世界通用)
最多三個字節來表示一個字符

三、代碼

import java.io.*;

class EncodeStream 
{
	public static void main(String[] args) 
	{
		
	}

	public static void readText() throws IOException
	{
		InputStreamReader isr=new InputStreamReader(new FileInputStream("gbk.txt","GBK");
		char[] buf=new char[10];
		int len=isr.read[buf];
		String str=new String(buf,0,len);
		System.out.println(str);
	}

	public static void writeText()throws IOException
	{
		OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("gbk.txt"),"UTF-8");

		osw.write("你好");
		osw.close();
	
	}
}

字符編碼

一、概述
編碼:字符串 變 字節數組
String-->byte[];   str.getBytes();

解碼:字節數組 變 字符串
byte[]-->String;   new String(byte[]);

二、代碼

import java.util.*;

class EncodeStream1  
{
	public static void main(String[] args) throws Exception
	{
		String s="你好";

		byte[] b1=s.getBytes("GBK");//默認爲GBK進行編碼

		//byte[] b1=s.getBytes("ISO8859-1");//會出亂碼

/*①*/	System.out.println(Arrays.toString(b1));//會輸出4個負數(-60,-29,-70,-61)

		String s1=new String(b1,"GBK");//默認爲GBK進行解碼
		
/*②*/	System.out.println(s1);//會輸出你好

		String s2=new String(b1,"ISO8859-1");//解碼錯誤的s2

/*③*/	System.out.println(s2);//會輸出????
		
		byte[] b2=s2.getBytes("ISO8859-1");//將s2按照ISO8859-1進行編碼

		String s3=new String(b2,"GBK");//再將編碼後的字節數組按照GBK進行解碼

/*④*/	System.out.println(s3);//會輸出"你好"

		String s4=new String(b1,"UTF-8");//將b1用UTF-8進行解碼

/*⑤*/	System.out.println(s4);//會輸出???

		byte[] b3=s4.getBytes("UTF-8");//將s4使用UTF-8進行編碼

		String s5=new String(b3,"GBK");//將b3按照GBK進行解碼

/*⑥*/	System.out.println(s5);//不會輸出"你好",而會輸出亂碼,這是因爲UTF-8也識別中文的原因。

	}
}

UTF-8修改版

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章