java讀取文件字符集示例方法
更新時間:2014年02月24日 09:39:55 作者:
這篇文章主要介紹了java讀取文件字符集的示例,需要的朋友可以參考下
復制代碼 代碼如下:
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;
//單獨出現(xiàn)BF以下的,也算是GBK
if (0x80 <= read && read <= 0xBF)
break;
if (0xC0 <= read && read <= 0xDF) {
read = bis.read();
if (0x80 <= read && read <= 0xBF)// 雙字節(jié) (0xC0 - 0xDF)
// (0x80 -
// 0xBF),也可能在GB編碼內(nèi)
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;
}
相關(guān)文章
Java微服務實戰(zhàn)項目尚融寶接口創(chuàng)建詳解
這篇文章主要介紹了Java微服務實戰(zhàn)項目尚融寶的接口創(chuàng)建流程,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08
詳解Java線程編程中的volatile關(guān)鍵字的作用
這篇文章主要介紹了Java線程編程中的volatile關(guān)鍵字的作用,針對其禁止進行指令重排序和讀寫內(nèi)存方面著重講解,需要的朋友可以參考下2015-12-12
Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法(下)
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)之常見排序算法(下),與之相對有(上),想了解的朋友可以去本網(wǎng)站掃搜,在這兩篇文章里涵蓋關(guān)于八大排序算法的所有內(nèi)容,需要的朋友可以參考下2023-01-01
SpringSession會話管理之Redis與JDBC存儲實現(xiàn)方式
本文將詳細介紹Spring Session的核心概念、特性以及如何使用Redis和JDBC來實現(xiàn)會話存儲,幫助開發(fā)者構(gòu)建更加健壯和可擴展的應用系統(tǒng),希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

