【发布时间】:2020-01-02 23:02:45
【问题描述】:
我正在尝试阅读textfile 并想做一些过滤。为此,我使用BufferedReader 读取文件并创建了一个名为"line" 的String 来读取所有行。我想检查line 是否以特定的string 开头(在我的情况下为“#”),并且它之后的line(下一行)不是以另一个特定的String 开头(在我的案例“h”)。如果“下一行”以“h”开头,则应删除该行。
所以基本上我想让每一行都均匀。
例子:
这是一个文本文件:
#line
ham
#line2
house
#line3
#line4
heart
#line5
hand
(对于这个例子第 4 行应该被删除)
我尝试过这样的事情:
if (line.startsWith("#") && nextline != "h"){
// remove this line
// There is no definition for "nextline"
}
阅读线:
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
position2string = String.valueOf(wrongpos + 1 + ".");
while ((line = br.readLine()) != null) {
if (line.startsWith("h")) {
lineStore.add(line);
}
if (line.startsWith("#")) {
line2 = line.replace("#EXTINF:-1,", "");
line3 = +richtigeposition + 1 + ". " + line2;
richtigeposition++;
namelist.add(line3);
arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.listitem, R.id.firsttext,
namelist);
mainlist.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
}
br.close();
} catch (Exception e) {
Log.e("MainAcvtivity", + e.toString());
}
编辑(感谢 Tim Biegeleisen,我找到了解决方案,但我得到 NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length() this Exception at bw.write(last); ,对不起,我很编程新手):
我当前的代码:
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
String line;
position2string = String.valueOf(wrongpos + 1 + ".");
while ((line = br.readLine()) != null) {
if (last != null && (!line.startsWith("h") || !lastPound)) {
bw.write(last);
}
lastPound = line.startsWith("#");
last = curr;
if (line.startsWith("h")) {
lineStore.add(line);
}
if (line.startsWith("#")) {
line2 = line.replace("#EXTINF:-1,", "");
line3 = +richtigeposition + 1 + ". " + line2;
richtigeposition++;
namelist.add(line3);
arrayAdapter = new ArrayAdapter<String>(
this,
R.layout.listitem, R.id.firsttext,
namelist);
mainlist.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
}
}
br.close();
//Exeption is here ==> bw.write(last);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
【问题讨论】:
标签: android line bufferedreader