How to Search for a String in a File and Write Matched Lines to Another File in Java?

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

Related Questions

⦿How to Develop a Turn-Based Game for Java ME on Gameloop?

Learn how to create a turnbased Java ME game using Gameloop with stepbystep instructions and code examples.

⦿How to Resolve the MappingException: No Dialect Mapping for JDBC Type 2002 in Hibernate

Learn how to fix the Hibernate MappingException related to JDBC type 2002. Expert solutions and common mistakes to avoid.

⦿What Are the Best Practices for Installing Third-Party Libraries in a Hosted Maven Repository?

Discover best practices for integrating thirdparty libraries into your hosted Maven repository enhancing project management and dependency management.

⦿How to Externalize web.xml `init-param` for Servlets Using Spring's DelegatingFilterProxy?

Learn how to externalize initparams from web.xml in Spring using DelegatingFilterProxy for improved configuration management.

⦿How to Effectively Implement Thinking in AppEngine for Your Applications?

Learn how to implement effective thinking processes in AppEngine applications to enhance performance and scalability.

⦿What Are Crit-bit Trees in Java and How Do They Work?

Explore the concept of Critbit trees in Java their structure advantages and implementation details. Learn how to utilize them effectively in coding.

⦿How to Add a JMenu to a JPanel in Java or Create a Drop Down Button?

Learn how to integrate JMenu into JPanel in Java and create a dropdown button effectively with examples.

⦿How to Implement Resumable File Uploads in Web Applications?

Learn how to implement resumable file uploads using JavaScript and HTML with our expert guide. Discover tips and common mistakes.

⦿What Changes Occurred with android.provider.Telephony in Android Development?

Explore the changes in android.provider.Telephony its uses potential issues and solutions in Android development.

⦿How to Implement the BitTorrent Peer Wire Protocol in Java?

Learn how to implement the BitTorrent Peer Wire Protocol using Java with detailed explanations and code examples.

© Copyright 2025 - CodingTechRoom.com