【问题标题】:remove lines that are odd from textfile android从文本文件android中删除奇怪的行
【发布时间】: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


    【解决方案1】:

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

    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();
    

    【讨论】:

    • 谢谢,但它仅适用于最低 API 26 。我的最低 API 是 API 21
    • @Creesch2.0 作为替代方案,您可以将 Files 方法更改为 Scanner 例如。如果您有兴趣,我可以修改答案。
    • 是的,请,我是新手,我遇到了这个问题。
    • @Creesch2.0 这些类可从 API 1 获得。
    【解决方案2】:

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

    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 开头的行)。

    【讨论】:

    • 我只是想将过滤后的行添加到数组列表中
    • 然后用代码替换对bw.write 的调用,将前一行添加到数组列表中。
    • 好的,我会这样做
    • 我在 bw.write(last); 的 while 循环后收到 NullPointerException;
    • 参考我之前的评论。
    猜你喜欢
    • 2015-02-09
    • 2010-12-09
    • 1970-01-01
    • 2014-04-30
    • 2014-02-14
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2014-02-14
    相关资源
    最近更新 更多