Remove a Specific Line from a File
When manipulating text files, the need to remove specific lines often arises. This question addresses the challenge of finding a line within a file and deleting it entirely.
The provided solution offers a simple approach. It reads the input file line by line and temporarily stores each line in an output file. During this process, any line that matches a specified string (e.g., "bbb") is intentionally omitted from the output. Once all lines are processed, the output file is renamed, overwriting the original file.
To implement this logic, the code leverages two classes: BufferedReader for reading lines from the input file and BufferedWriter for writing lines to the output file.
The key line in the code is:
if(trimmedLine.equals(lineToRemove)) continue;
This line checks if the current line matches the target line to be removed. If so, the continue statement is executed, skipping the writing of that line to the output file.
The remaining lines handle reading and writing operations and ensure that the output file is properly renamed to replace the original file.
By following these steps, it is possible to find and remove a specific line from a file, simplifying text manipulation tasks.
The above is the detailed content of How Can I Remove a Specific Line from a Text File?. For more information, please follow other related articles on the PHP Chinese website!