从文本文件中删除奇数行 android

remove lines that are odd from textfile android

我正在尝试阅读 textfile 并想进行一些过滤。为此,我使用 BufferedReader 来读取文件并创建了一个名为 "line"String 来读取所有行。我想检查 line 是否以特定的 string 开头(在我的例子中是“#”)并且它之后的 line(下一行)不是以另一个特定的开头String(在我的例子中 "h")。如果 "the next line" 以 "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();
        }

这是使用标准 BufferedReaderBufferedWriter 的简单方法。我们可以迭代文件,跟踪上一行是否以 # 开头,以及跟踪上一行的内容。对于读取的每一行,如果前一行 不是 # 开头,则当前行不以 [=15= 开头],然后写上一行。否则,前一行将被省略,有效地将其从新的输出文件中删除。

boolean lastPound = false;
String last;
String curr;
List<String> lines = new ArrayList<>();

try (FileReader reader = new FileReader("in.txt");
     BufferedReader br = new BufferedReader(reader)) {

        String line;
        while ((line = br.readLine()) != null) {
            if (last != null && (!line.startsWith("h") || !lastPound)) {
                lines.add(last);
            }
            lastPound = line.startsWith("#");
            last = curr;
        }
        lines.add(last);
}
catch (IOException e) {
    System.err.format("IOException: %s%n", e);
}

请注意,我们还在 while 循环之后将最后一行添加到列表中。文件的最后一行总是被写入,因为它后面没有另一行(因此后面不能跟以 h 开头的行)。

您可以用另一种方式来完成,这可能会节省您的时间和一些代码行。您可以将所有文件行放入一个列表中,然后与之交互会容易得多:

List<String> lines = Files.readAllLines(Paths.get(*path_to_file*), Charset.defaultCharset());

将文件行存储到 List 后,您就可以遍历它以搜索所需的行。为避免 NullPointerExceptionIndexOutOfBoundsException 不要忘记指定右边界。

for (int i = 0; i < lines.size() - 1; i++) {
    if (lines.get(i).startsWith("#") && !lines.get(i + 1).startsWith("h")) {
        lines.remove(i+1);
    }
}

之后,您可以将列表存储到文件中:

Files.write(Paths.get(*path_to_file*), lines);

我测试了它,输出看起来像这样:

---更新---

要执行 IO 操作,您可以使用 ScannerFileWriter:

List<String> lines = new ArrayList<>();

Scanner s = new Scanner(new File("in.txt"));

while (s.hasNext()) {
    lines.add(s.next());
}

s.close();

对于输出:

FileWriter writer = new FileWriter("out.txt");

for (String str : lines) {
    writer.write(str + System.lineSeparator());
}

writer.close();