0

I need to remove lines from txt file a

FileReader fr= new FileReader("Name3.txt");

BufferedReader br = new BufferedReader(fr);

String str = br.readLine();

br.close();

and I don't know the continue of the code.

ezscript
  • 17
  • 6

1 Answers1

0

You can read all lines and store them in a list. Whilst you're storing all lines, assuming you know the line you want to remove, simply check for the lines you don't want to store, and skip them. Then write the list content to a file.

    //This is the file you are reading from/writing to
    File file = new File("file.txt");
    //Creates a reader for the file
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";

    //This is your buffer, where you are writing all your lines to
    List<String> fileContents = new ArrayList<String>();

    //loop through each line
    while ((line = br.readLine()) != null) {
        //if the line we're on contains the text we don't want to add, skip it
        if (line.contains("TEXT_TO_IGNORE")) {
            //skip
            continue;
        }
        //if we get here, we assume that we want the text, so add it
        fileContents.add(line);
    }

    //close our reader so we can re-use the file
    br.close();

    //create a writer
    BufferedWriter bw = new BufferedWriter(new FileWriter(file));

    //loop through our buffer
    for (String s : fileContents) {
        //write the line to our file
        bw.write(s);
        bw.newLine();
    }

    //close the writer
    bw.close();
kbz
  • 984
  • 2
  • 12
  • 30
  • i didn't understand ur code can u explain me – ezscript Aug 16 '17 at 17:25
  • Sure, I have added comments to the code – kbz Aug 16 '17 at 23:46
  • In Java 8, the entire reading segment can basically be replaced with `List fileContents = Files.lines(file.toPath()).filter(line -> !line.contains("TEXT_TO_IGNORE")).collect(Collectors.toCollection(ArrayList::new));` – Tim M. Aug 17 '17 at 16:47