详细解决方案
检测某个txt文件是gbk编码还是utf8编码
热度:83 发布时间:2024-01-21 15:26:27.0
阅读器需要用到
|
|
public String getCharset() throws IOException {
mBookFile = new RandomAccessFile(strFilePath, "r");byte[] bytes = new byte[200];mBookFile.read(bytes);mCharset = EncodeDetector.detect(bytes); Log.e("TAG", "The charset is " + mCharset);return mCharset; }
|
123456789
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package com.example.novelreader;public class EncodeDetector {
public final static String UTF8 = "UTF-8"; public final static String GBK = "GBK"; /**
* 检测
* @param data
* @return
*/public static String detect(byte[] data) {
int utfCount = 0;boolean isUtf8 = true;for (int i = 0; i < data.length; i++) {
byte b0 = data[i];if (utfCount == 0) {
if ((b0 & 0x80) != 0) {
if ((b0 & 0xE0) == 0xC0) {
utfCount = 1;} else if ((b0 & 0xF0) == 0xE0) {
utfCount = 2;} else if ((b0 & 0xF8) == 0xF0) {
utfCount = 3;} else if ((b0 & 0xFC) == 0xF8) {
utfCount = 4;} else if ((b0 & 0xFE) == 0) {
utfCount = 5;} else {
isUtf8 = false;break;}}} else {
if ((b0 & 0xC0) != 0x80) {
isUtf8 = false;break;}--utfCount;}}if (isUtf8) {
return UTF8;} else {
return GBK;}}
}
|