2010-05-18

利用 Java 獲取文件的編碼類型 (Use Java to get the file encoding)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public static String fileEncoding(File file) throws FileNotFoundException, IOException{
    FileInputStream in = new FileInputStream(file);
    int[] bytes = new int[3];
    for (int ch, i = 0; (ch = in.read()) > 0 && i < bytes.length; i++){
        bytes[i] = ch;
    }
    String encoding = "ANSI";
    if (bytes[0] == 0xff && bytes[1] == 0xfe){
        encoding = "Unicode";
    } else if (bytes[0] == 0xfe && bytes[1] == 0xff){
        encoding = "Unicode Big-Endian";
    } else if (bytes[0] == 0xef && bytes[1] == 0xbb && bytes[2] == 0xbf){
        encoding = "UTF-8";
    }
    return encoding;
}

沒有留言 :

張貼留言