阅读器需要用到
1 2 3 4 5 6 7 8 9 |
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;
}
|
1 2 3 4 5 6 7 8 9 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;
}
}
}
|