只有ansi編碼的文本才能打開,其余編碼會導致亂碼
代碼如下:
private void saveChapter(File book, String md5) throws IOException {
String regex = "第.{1,7}章.{0,}\r\n";
String encoding;
InputStream fis;
String inn;
FileInputStream fiss = new FileInputStream(book);
inn = readShaderFromRawResource(fiss);
fis = new ByteArrayInputStream(inn.getBytes("utf-8"));
byte[] buf = new byte[4096];
UniversalDetector detector = new UniversalDetector(null);
int nread;
while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
detector.dataEnd();
encoding = detector.getDetectedCharset();
if (encoding == null || encoding.length() == 0)
encoding = "utf-8";
fis.close();
fis = null;
int chapterPageIndex = 0;
String title = null;
StringBuilder contentBuilder = new StringBuilder();
fiss = new FileInputStream(book);
inn = readShaderFromRawResource(fiss);
fis = new ByteArrayInputStream(inn.getBytes("utf-8"));
InputStreamReader inputreader = new InputStreamReader(fis, encoding);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while ((line = buffreader.readLine()) != null) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(line);
if (m.find()) {
String temp = line.trim().substring(0, line.trim().indexOf("第"));
if (temp != null && temp.trim().length() > 0) {
contentBuilder.append(temp);
}
if (contentBuilder.toString().length() > 0) {
if (contentBuilder.toString().replaceAll(" ", "").trim().length() > 0) {
saveDurChapterContent(md5, chapterPageIndex, title, contentBuilder.toString());
chapterPageIndex++;
}
contentBuilder.delete(0, contentBuilder.length());
}
title = line.trim().substring(line.trim().indexOf("第"));
} else {
if (line.trim().length() == 0) {
if (contentBuilder.length() > 0) {
contentBuilder.append("\r\n\u3000\u3000");
} else {
contentBuilder.append("\r\u3000\u3000");
}
} else {
String lines = line.replace(" ", "\r\n");
contentBuilder.append(lines);
if (title == null) {
title = line.trim();
}
}
}
}
if (contentBuilder.length() > 0) {
saveDurChapterContent(md5, chapterPageIndex, title, contentBuilder.toString());
contentBuilder.delete(0, contentBuilder.length());
title = null;
}
buffreader.close();
inputreader.close();
fis.close();
fis = null;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/42437.html
標籤:Android
上一篇:有沒有android的大佬
