Search code examples
androidlinebufferedreader

remove lines that are odd from textfile android


I'm trying to read a textfile and wanted to do some filtering. For that I used a BufferedReader to read the file and created a String called "line" to read all lines. I would like to check if a line starts with a specific string (in my case "#") and the line after it (the next line) doesn't start with another specific String (in my case "h"). And if the "the next line" starts with "h" the line should be removed.

So basically I want to make every line even.

Example:

This is a text file:

#line
ham
#line2
house
#line3
#line4
heart
#line5
hand

(for this example line4 should be removed)

I tried something like this:

if (line.startsWith("#") && nextline != "h"){
                        // remove this line
                        // There is no definition for "nextline"
                    }

for reading lines:

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

Edit (Thanks to Tim Biegeleisen, I found a solution, but I'm getting NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length() this Exception at bw.write(last); , sorry I'm quite new to programming) :

My current code:

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

Solution

  • You could do it in another way that probably will save your time and some code lines. You could get all file lines into a list and then it would be much easier to interact with it:

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

    After storing your file lines into List you become able to iterate thro it to search for needed lines. To avoid NullPointerException or IndexOutOfBoundsException don't forget to specify right bounds.

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

    After that, you're able to store your List into a file:

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

    I tested that and output looked like that:

    enter image description here

    --- Update ---

    To perform IO operations you could use Scanner and FileWriter:

    List<String> lines = new ArrayList<>();
    
    Scanner s = new Scanner(new File("in.txt"));
    
    while (s.hasNext()) {
        lines.add(s.next());
    }
    
    s.close();
    

    And for output:

    FileWriter writer = new FileWriter("out.txt");
    
    for (String str : lines) {
        writer.write(str + System.lineSeparator());
    }
    
    writer.close();