Home > Java > javaTutorial > How Can I Efficiently Remove a Specific Line from a Text File in Java?

How Can I Efficiently Remove a Specific Line from a Text File in Java?

Susan Sarandon
Release: 2024-12-04 06:14:15
Original
748 people have browsed it

How Can I Efficiently Remove a Specific Line from a Text File in Java?

Removing a Line from a File

In various programming scenarios, you may need to modify text files by removing specific lines. This can be achieved through various approaches.

One effective method to remove a line from a file is by reading the file line by line, skipping any lines that match the line you wish to delete. Here's an example implementation in Java:

File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");

BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));

String lineToRemove = "bbb";
String currentLine;

while((currentLine = reader.readLine()) != null) {
    // trim newline when comparing with lineToRemove
    String trimmedLine = currentLine.trim();
    if(trimmedLine.equals(lineToRemove)) continue;
    writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close(); 
reader.close(); 
boolean successful = tempFile.renameTo(inputFile);
Copy after login

This code iterates through each line in the input file, checking if it matches the line to be removed. If it does not match, the line is written to a temporary file. This process effectively removes the desired line from the input file. Finally, the temporary file is renamed to replace the input file, ensuring that the line is permanently removed.

The above is the detailed content of How Can I Efficiently Remove a Specific Line from a Text File in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template