Question
How can I search for a specific string in a file and write the lines that match to another file using Java?
BufferedReader reader = new BufferedReader(new FileReader("input.txt")); PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
Answer
Searching for a string in a file and writing the matched lines to another file is a common task in Java. This process involves reading a file line by line, checking if each line contains the specified string, and then writing those lines to a new file if a match is found.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class StringSearcher {
public static void main(String[] args) {
String searchString = "your_search_string";
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
PrintWriter writer = new PrintWriter(new FileWriter("output.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchString)) {
writer.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Causes
- The source file does not exist or is improperly formatted.
- The search string is not found in any line of the file.
- Improper handling of file I/O exceptions.
Solutions
- Use `BufferedReader` to read the file efficiently line by line.
- Utilize `PrintWriter` to create and write to the output file easily.
- Implement exception handling to manage potential file I/O errors.
Common Mistakes
Mistake: Forgetting to close file resources which can lead to memory leaks.
Solution: Use try-with-resources to automatically manage closing files.
Mistake: Trying to read a non-existent file without handling exceptions.
Solution: Always check if the file exists or wrap file operations in a try-catch block.
Helpers
- Java file I/O
- search string in file Java
- write to file Java
- Java BufferedReader
- Java PrintWriter