0

let's say I have a line: "Hello Jason, How are you today?" inside a text file. And let's say I don't know what that line is, but I have one string from it, for example "are", and the word "are" is only showing in that line inside this text. How would I be able to find this place + delete the whole line without knowing the other words in the same line?

I've tried looking online for solutions, but I could only find solutions to my problem if I'd have known the whole line.

BufferedReader bufferedReader = new BufferedReader(new 
FileReader("Hello.txt"));
String currentLine;
    while((currentLine = bufferedReader.readLine()) != null){
        if(currentLine.contains("are")){
        //Delete the whole line.
        }
}

Expected results: delete a line that contains a word. Errors: None.

Destinations
  • 11
  • 1
  • 5
  • 4
    see this answer: https://stackoverflow.com/questions/1377279/find-a-line-in-a-file-and-remove-it –  Sep 17 '19 at 14:27
  • Instead of "deleting" the line, instead store the lines you want to keep in a list... and then when you are done iterating over each line, rewrite all the lines you want to keep to a file. – RobOhRob Sep 17 '19 at 14:27
  • Also, why don't you know the other words in the line? They are in `currentLine`? – RobOhRob Sep 17 '19 at 14:33
  • @RobOhRob True, I've tried doing what vmarinescu suggested, and it doesn't work, I also don't know what line.seperater does or anything. – Destinations Sep 17 '19 at 16:08

1 Answers1

0

Here is the way I would do it. Store the lines you want to keep in a list. Then simply rewrite that list to the file.

// using for loop
private static void option1( final File FILE ) throws IOException {

    // read all lines from file into a list
    List<String> fileContent = new ArrayList<>( Files.readAllLines( FILE.toPath(), StandardCharsets.UTF_8 ) );

    List<String> linesToWrite = new ArrayList<>(); // new list of lines that we want to keep
    for ( String line : fileContent ) {

        if ( !line.contains( "are" ) ) {
            // line doesn't contain are, so add to our list of lines to keep
            linesToWrite.add( line );
        }

    }

    // write the lines we want back to the file
    Files.write( FILE.toPath(), linesToWrite, StandardCharsets.UTF_8 );
}

// using Java 8 Streams
private static void option2( final File FILE ) throws IOException {

    // read all lines from file into a list
    List<String> fileContent = new ArrayList<>( Files.readAllLines( FILE.toPath(), StandardCharsets.UTF_8 ) );

    // filter using streams
    fileContent = fileContent.stream()
            .filter( line -> !line.contains( "are" ) ) // filter out all lines that contain are
            .collect( Collectors.toList() );

    // write the lines we want back to the file
    Files.write( FILE.toPath(), fileContent, StandardCharsets.UTF_8 );
}
RobOhRob
  • 585
  • 7
  • 17