安卓逐行读取txt文件数据
发布网友
发布时间:2022-04-21 14:25
我来回答
共1个回答
热心网友
时间:2022-04-23 05:49
试着写了下,实现了。思路就是用IO流,BufferedReader类的readLine()方法来逐行读取txt文件因为章节标题一般都是独占一行的,然后用正则表达式来判断,代码如下(顺便给每章加了跳转标示,用offset记录下字节数,之后用dr.skip(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();
}
}
});
追问
能帮我检查一下我这个方法能实现吗