How to print all the lines that contain a search word in text file in Java

1 Answer

0 votes
package javaapplication1;

import java.io.*;

public class JavaApplication1 
{
    public static void main(String[] args) 
    {
        try 
        {
            File file = new File("d:\\test.txt");
            FileReader fr = new FileReader(file);
            try (BufferedReader br = new BufferedReader(fr)) 
            {
                String line, word = "three";
                
                while((line = br.readLine()) != null) 
                    if (line.contains(word)) 
                        System.out.println(line);
            }
            catch (Exception e)
            {
                System.out.println(e.toString());
            }
        }
        catch (Exception e) 
        {
            System.out.println("Error reading file: " + e.getMessage());   
        }
    }
}

/*

run:

Text File Line three

*/



answered Mar 8, 2015 by avibootz
...