天天看點

Java系列(50)——字元集編碼

本系列部落格彙總在這裡:Java系列_彙總

目錄

  • 一、字元集編碼概述
  • 二、使用給定編碼方式來寫入和讀取檔案
    • 1、寫入
    • 2、讀取
  • 三、字元串編碼解析
  1. 存儲

    在計算機中存儲字元都是存儲的字元所對應的數值,以二進制的形式表示。

  2. 展示

    去相關的編碼表中去查找該值(存儲的值)所對應的字元。

    • 0,a,A用一個字元存儲。
    • 中間的範圍用二個位元組。
    • 中文就使用 3 個位元組。
    • 寫入的編碼和讀取的編碼必須要一緻,否則會有亂碼。

  • 示例
    public static void main(String[] args)
    {
    	PrintWriter pw = null;
    	try
    	{
    		// 預設編碼就是 GBK
    		// 把“魏宇軒”轉換成位元組然後按照 UTF-8 的編碼方式存儲到檔案中
    		pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("f.txt"), "UTF-8"), true);
    		pw.println("魏宇軒");
    
    	} catch (UnsupportedEncodingException e)
    	{
    		e.printStackTrace();
    	} catch (FileNotFoundException e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if (pw != null)
    			pw.close();
    	}
    }
               
    Java系列(50)——字元集編碼

  • public static void main(String[] args)
    {
    	BufferedReader br = null;
    	try
    	{
    		br = new BufferedReader(new InputStreamReader(new FileInputStream("f.txt"), "UTF-8"));
    		char[] chs = new char[1024];
    		int len = br.read(chs);
    		System.out.println( new String(chs,0,len));
    	} catch (Exception e)
    	{
    		e.printStackTrace();
    	} finally
    	{
    		if (br != null)
    		{
    			try
    			{
    				br.close();
    			} catch (IOException e)
    			{
    				e.printStackTrace();
    			}
    		}
    	}
    }
               
    Java系列(50)——字元集編碼
    注意:寫入和讀取的字元編碼務必一緻,否則會出現亂碼!
  • public static void main(String[] args) throws Exception
    {
    	String str = "魏宇軒";
    	
    	
    	// 使用GBK編碼方式把字元串編碼為位元組
    	byte[] bs = str.getBytes();
    	
    	for (int i = 0; i < bs.length; i++)
    	{
    		System.out.print(bs[i] + "\t");
    	}
    	
    	System.out.println("\n------------------------------解碼-------------------------------");	
    	// 使用 GBK 編碼方式解碼
    	String str1 = new String(bs, "GBK");
    	System.out.println("\n"+str1);
    	System.out.println("\n\n");
    	
    	
    	// 使用UTF-8編碼方式把字元串編碼為位元組
    	byte[] bs1 = str.getBytes("UTF-8");
    	for (int i = 0; i < bs1.length; i++)
    	{
    		System.out.print(bs1[i] + "\t");
    	}
    	
    	System.out.println("\n-------------------------------解碼-------------------------------");	
    	// 使用 UTF-8 編碼方式解碼
    	String str2 = new String(bs1, "UTF-8");
    	System.out.println("\n"+str2);
    }
               
    Java系列(50)——字元集編碼