Fady E
Fady E

Reputation: 346

Find a word in a File and print the line that contains it in java

Using command line, I am supposed to enter a file name that contains text and search for a specific word.

foobar file.txt

I started writing the following code:

import java.util.*;
import java.io.*;

class Find {
    public static void main (String [] args) throws FileNotFoundException {
        String word = args[0];
        Scanner input = new Scanner (new File (args[1]) );
        while (input.hasNext()) {
            String x = input.nextLine();    
        }
    }
}

My program is supposed to find word and then print the whole line that contains it. Please be specific since I am new to java.

Upvotes: 2

Views: 7387

Answers (2)

Zephyr
Zephyr

Reputation: 10253

You are already reading in each line of the file, so using the String.contains() method will be your best solution

if (x.contains(word) ...

The contains() method simply returns true if the given String contains the character sequence (or String) you pass to it.

Note: This check is case sensitive, so if you want to check if the word exists with any mix of capitalization, just convert the strings to the same case first:

if (x.toLowerCase().contains(word.toLowerCase())) ...

So now here is a complete example:

public static void main(String[] args) throws FileNotFoundException {

    String word = args[0];

    Scanner input = new Scanner(new File(args[1]));

    // Let's loop through each line of the file
    while (input.hasNext()) {
        String line = input.nextLine();

        // Now, check if this line contains our keyword. If it does, print the line
        if (line.contains(word)) {
            System.out.println(line);
        }
    }
}

Upvotes: 4

Khalid Shah
Khalid Shah

Reputation: 3232

Firest you have to open file and then read it line by line and check that word is in that line on not. see the code below.

class Find {
    public static void main (String [] args) throws FileNotFoundException {
          String word = args[0]; // the word you want to find
          try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
          String line;
          while ((line = br.readLine()) != null) { //read file line by line in a loop
             if(line.contains(word)) { // check if line contain that word then prints the line
                  System.out.println(line);
              } 
          }
       }
    }
}

Upvotes: 1

Related Questions