1. 程式人生 > >《Java》Java“字串操作”實際應用——形成GBK編碼和UTF-8編碼的文字檔案,通過其二進位制資料觀察兩種編碼的不同

《Java》Java“字串操作”實際應用——形成GBK編碼和UTF-8編碼的文字檔案,通過其二進位制資料觀察兩種編碼的不同

一、任務目標

    完成一個java application應用程式,可以把GBK編碼的漢字字串與UTF-8編碼的漢字字串相互轉換。並配合寫檔案操作形成不同編碼格式的文字檔案,可以通過其二進位制資料觀察兩種編碼的不同。

二、程式設計思路

    博主將“程式設計思路”以流程圖的方式說明,如下圖:

三、程式碼實現

文字檔案(binary.txt):
在這裡插入圖片描述
程式程式碼:

import java.io.*;  //匯入IO流
import java.util.Scanner;  //匯入Scanner類

public class Sconvert
{ //建立類 /** * @param args * @return * @throws IOException */ //"寫二進位制數"函式 public static void writebi(String str,String code){ String result = null; File file = new File("F:/TCC/binary.txt");//建立檔案物件 try{ //File類異常捕捉 FileWriter fw = new FileWriter(file,true);//建立FileWriter物件fw BufferedWriter bufw =
new BufferedWriter(fw);//建立BufferedWriter物件bufw bufw.write("“"+str+"”"+"的"+"<"+code+">"+"二進位制數:");//向binary.txt中寫字首 try{ //getBytes異常捕捉 //通過getBytes()方法,以指定的字符集(即編碼方式)獲取字元 byte[] byt = str.getBytes(code); for(int k=0;k<byt.length;k++) { //通過toBinaryString()方法將字元轉換為二進位制數 result =
Integer.toBinaryString(byt[k]&0xff); bufw.write(result+" ");//將轉換後二進位制數寫入binary.txt中 } bufw.newLine();//寫入空白行 bufw.newLine(); System.out.println("寫入成功!"); }catch(UnsupportedEncodingException e){ System.out.println("不支援的字符集"); } bufw.close(); }catch(Exception e1){ e1.printStackTrace(); } } //"編碼方式選擇"函式 public static String coding(){ String code = null; System.out.println("請選擇編碼格式:"+"\n"+"1:GBK"+"\n"+"2:UTF-8"); Scanner scan = new Scanner(System.in); switch(scan.nextInt()){ case 1: code = "GBK"; break; case 2: code = "UTF-8"; break; } return code; } public static void main(String[] args){ String str = null; String code = null; int j = 0; code = coding();//將"編碼方式選擇"函式放回的字串存入code中 System.out.println("請輸入內容:"); Scanner scan = new Scanner(System.in); String strs = scan.next(); for(int i = 0;i<strs.length();i++) { str = strs.substring(j+i,i+1);//通過substring()方法取出字串strs指定位置的字元 writebi(str,code);//呼叫“寫二進位制數”函式 } } }

執行結果:
在這裡插入圖片描述
在這裡插入圖片描述

四、GBK編碼與UTF-8編碼的區別

從上圖分析可以看出(字母“A”首位的0別省略):

  1. GBK編碼專門用來解決中文編碼的,中文使用16位(即兩個位元組),英文使用8位(即一個位元組)。
  2. UTF-8 編碼是用以解決國際上字元的一種多位元組編碼,中文使用24位(三個位元組),對英文使用8位(即一個位元組)來編碼。