2024-05-25 04:28:53
试着写了下,实现了。思路就是用IO流,BufferedReader类的readLine()方法来逐行读取txt文件因为章节标题一般都是独占一行的,然后用正则表达式来判断,代码如下(顺便给每章加了跳转标示,用offset记录下字节数,之后用dr.skip(offset)方法就能直接跳转到该行):
截图,章节前面的数字是offset,用来当跳转标识
new Handler().post(new Runnable()
@Override
public void run() {
// TODO Auto-generated method stub
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/全职高手.txt");
if (!file.exists()) {
return;
}
FileInputStream fis;
final String RE = "([第].{1,5}[章])(.+)";
try {
fis = new FileInputStream(file);
BufferedReader dr = new BufferedReader(
new InputStreamReader(fis, "GBK"));
String line = null;
long offset = 0;
while ((line = dr.readLine()) != null) {
if (line.trim().matches(RE)) {
Log.d(offset + "", line.trim());
}
;
offset = offset + line.length() + 2;
}
dr.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});