隨堂筆記:文件的編碼

package com.imooc.io;

import java.io.UnsupportedEncodingException;

public class EncodeDemo {
	public static void main(String[] args) throws UnsupportedEncodingException {
		String s = "慕課ABC";
		System.out.printf("Original string: %n[%s]%n", s);
		
		System.out.println("Charset default:");
		printBytes(s.getBytes());             // [c4 bd bf ce 41 42 43]
		
		System.out.println("Charset gbk:");
		printBytes(s.getBytes("gbk"));        // [c4 bd bf ce 41 42 43]

		System.out.println("Charset utf-8:");
		printBytes(s.getBytes("utf-8"));      // [e6 85 95 e8 af be 41 42 43]
		
		System.out.println("Charset utf-16be:");
		printBytes(s.getBytes("utf-16be"));   // [61 55 8b fe 0 41 0 42 0 43]
	}

	private static void printBytes(byte[] bytes) {
		StringBuilder result = new StringBuilder();
		for (byte b : bytes) {
			// Show each byte in form of HEX-numbered string
			result.append(Integer.toHexString(b & 0xff)).append(" ");
		}
		System.out.printf("[%s]%n", result.toString().trim());
	}
	
	/* Note:
	 * -----------------
	 * 1. 中文OS創建文本文件時,編碼默認爲ANSI,即GBK編碼;聯通、聯按utf-8保存僅爲巧合
	 * 2. Java 採用雙字節編碼 UTF-16BE,其中文、英文均佔兩個字節(61 55、0 41)
	 * 3. 按 utf-8 編碼,一箇中文佔 3 個字節,英文佔 1 個字節
	 * 4. string -> bytes[](按charset編碼):byte[] bytes = str.getBytes(charset);
	 * 5. bytes[] -> string(按charset編碼):String string = new String(bytes, charset);
	 */
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章