1. Introduction
In Java, if you want to read a file line by line and delete specific lines as you read, you typically need to:
- Read the file line by line using a
BufferedReader
. - Store only the lines you want to keep.
- Overwrite the file with the filtered content using a
BufferedWriter
.
This method ensures that the unwanted line(s) are removed from the file, while the remaining content is preserved.
2. Step-by-Step Approach
✅ Steps:
- Open the file for reading.
- Read each line and decide whether to keep or skip it.
- Store the lines to keep in a list or collection.
- Overwrite the file with only the lines you kept.
3. Java Code Example
Here is a full example that reads a file and deletes a specific line:
java
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class FileReadAndDeleteLine {
public static void main(String[] args) {
String filePath = "path/to/your/file.txt";
String lineToDelete = "line you want to delete"; // Replace with your line content
File file = new File(filePath);
List<String> lines = new ArrayList<>();
// Step 1: Read the file and collect lines to keep
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.equals(lineToDelete)) {
lines.add(line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Step 2: Write the kept lines back to the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. How It Works
- Reading the file:
- The
BufferedReader
reads each line of the file. If the line matches the target line to delete, it's skipped. - Storing lines:
- Lines that do not match are added to a list.
- Writing back:
- After reading is complete, the
BufferedWriter
rewrites the file with only the kept lines.
5. Output Example
Assume the file originally contains:
nginx
Hello
World
Test
Java
If lineToDelete = "World"
, after execution, the file will become:
nginx
Hello
Test
Java
6. Notes
- Overwriting the file: This approach fully replaces the file content.
- Exact match: The deletion is based on exact string match (
String.equals()
). - Case sensitivity: This comparison is case-sensitive. If needed, convert both strings to lower/upper case before comparison.
- Large files: For huge files, consider using a temporary file to reduce memory usage or use streaming techniques.
7. Extensions
- Delete lines based on regex patterns.
- Keep a log of deleted lines.
- Support bulk deletion (e.g., delete all lines that start with "temp").