国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java讀取文件字符集示例方法

2019-11-26 15:40:24
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

public static String getCharset(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        try {
            boolean checked = false;
            BufferedInputStream bis = new BufferedInputStream(
                  new FileInputStream(file));
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1]
                == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF && first3Bytes[1]
                    == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                int loc = 0;
                while ((read = bis.read()) != -1) {
                    loc++;
                    if (read >= 0xF0)
                        break;
                    //單獨出現BF以下的,也算是GBK
                    if (0x80 <= read && read <= 0xBF)
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF)// 雙字節 (0xC0 - 0xDF)
                            // (0x80 -
                            // 0xBF),也可能在GB編碼內
                            continue;
                        else
                            break;
                     // 也有可能出錯,但是幾率較小
                    } else if (0xE0 <= read && read <= 0xEF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
                System.out.println(loc + " " + Integer.toHexString(read));
            }
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return charset;
    }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 聂拉木县| 唐山市| 治多县| 江陵县| 高台县| 定陶县| 府谷县| 都江堰市| 白水县| 桐庐县| 大城县| 邛崃市| 利津县| 湖口县| 永嘉县| 兰州市| 琼结县| 苍溪县| 娄烦县| 通河县| 弥勒县| 宜州市| 伊吾县| 巴林左旗| 项城市| 鄂温| 望谟县| 理塘县| 遵化市| 富蕴县| 贺州市| 丰宁| 昭觉县| 甘德县| 成安县| 六安市| 龙南县| 清水县| 德钦县| 中超| 裕民县|