Find line in text file, delete line and lines below

I have some code to find a line in a text file, print the line the line is in, then print 5 lines below it. However, I need to change it so that instead of printing, it will delete / delete the line after the line is found. How can i do this?

File file = new File("./output.txt");
Scanner in = null;
try {
    in = new Scanner(file);
    while (in.hasNext()) {
        String line = in.nextLine();
        if (line.contains("(1)")) {
            for (int a = 0; in.hasNextLine() && a < 6; a++) {
                System.out.println(line);
                line = in.nextLine();
            }
        }
    }
} catch (Exception e) {
}

      

+3


source to share


3 answers


Find a small snippet where you can start.

Assuming yours question.txt

has the following entry.

line 1
line 2
line 3 (1)
line 4
line 5
line 6
line 7
line 8
line 9
line 10

      

This snippet will print all lines and skip a line line 3 (1)

, as well as five lines after.



List<String> lines = Files.readAllLines(Paths.get("question.txt"), Charset.defaultCharset());
for (int i = 0; i < lines.size(); i++) {
    if (lines.get(i).contains("(1)")) {
        i = i + 6;
    }
    System.out.println(lines.get(i));
}

      

Output

line 1
line 2
line 9
line 10

      

Saving the lines in a file is up to you.

+3


source


My suggestion is you first declare and initialize the StringBuilder

say output

before your code:

StringBuilder output = new StringBuilder();

      

Now after closing the statement, if

before closing the loop, while

add a line in output

and add "\n"

to the end like this:

output.append(line+"\n");

      



Now, finally, after your code you posted, create a FileWriter

say writer

and then use a write to write output

like below:

try(FileWriter writer = new FileWriter(file, false)){
   writer.write(output);
}catch IOException(e){
   e.printStackTrace();
}

      

Also remember to remove or comment out the next line if you don't want them to be printed in the output.

System.out.println(line);

      

+1


source


SubOtimal has a good, concise answer that will work most of the time. The following is more complex, but avoids loading the entire file into memory. This is probably not a problem for you, but just in case ...

public void deleteAfter(File file, String searchString, int lineCountToDelete) {
    // Create a temporary file to write to
    File temp = new File(file.getAbsolutePath() + ".tmp");
    try (BufferedReader reader = new BufferedReader(new FileReader(file));
         PrintWriter writer = new PrintWriter(new FileWriter(temp)) ) {

        // Read up to the line we are searching for
        // and write each to the temp file
        String line;
        while((line = reader.readLine()) != null && !line.equals(searchString)){
            writer.println(line);
        }

        // Skip over the number of lines we want to "delete"
        // as well as watching out for hitting the end of the file
        for(int i=0;i < lineCountToDelete && line != null; i++){
            line = reader.readLine();
        }

        // Write the remaining lines to the temp file.
        while((line = reader.readLine()) != null){
            writer.println(line);
        }

    } catch (IOException e) {
        throw new IllegalStateException("Unable to delete the lines",e);
    }

    // Delete the original file
    if(!file.delete()){
        throw new IllegalStateException("Unable to delete file: " + file.getAbsolutePath());
    }

    // Rename the temp file to the original name
    if(!temp.renameTo(file)){
        throw new IllegalStateException("Unable to rename " +
                temp.getAbsolutePath() + " to " + file.getAbsolutePath());
    }
}

      

I tested this with several conditions, including a line that doesn't exist, a line at the end, and a line with fewer lines left below the number to skip. All worked and gave the appropriate results.

0


source







All Articles