当前位置: 编程技术>java/j2ee
java读取文件字符集示例方法
来源: 互联网 发布时间:2014-11-02
本文导语: 代码如下:public static String getCharset(File file) { String charset = "GBK"; byte[] first3Bytes = new byte[3]; try { boolean checked = false; BufferedInputStream bis = new BufferedInputStream( ...
代码如下:
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-8LE";
checked = true;
} else if (first3Bytes[0] == (byte) 0xFE && first3Bytes[1]
== (byte) 0xFF) {
charset = "utf-8BE";
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