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
Susan SarandonOriginal
2024-12-04 06:14:15757browse

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

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!

Statement:
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