Paul
Paul

Reputation: 49

Java- Searching for a string in text file, then print line

I am writing a code where the user can search a text file for a particular string, (case insensitive) and it prints the entire line where the string is found. My code snippet is here:

public static void search() throws FileNotFoundException
{
Scanner input = new Scanner( System.in );
int fieldNumber = 0;



if ( fieldNumber == 0 )
{
    System.out.println("Enter field value to search for: ");
    String fieldValue = input.next();
    if ("orange".equalsIgnoreCase(fieldValue))
    {
     // Here is where I am stuck. 
       {

       }

Upvotes: 1

Views: 7340

Answers (2)

ganeshvjy
ganeshvjy

Reputation: 407

    try
    {
        Scanner file = new Scanner(new File("file.txt"));
        String str = str.nextLine();
        System.out.print("Enter search ");
        Num = input.nextInt();

        if ( Num == 0 )
        {
            System.out.println("Enter search for: ");
            String Value = input.next();

            while (file.hasNextLine())
            {
                final String lineFromFile = file.nextLine();
                if(lineFromFile.contains(Value))
                {
                    System.out.println("file.txt");
                    System.out.println(lineFromFile);
                    break;
                }

Upvotes: 1

Dean J
Dean J

Reputation: 40288

When the Scanner reads a line, it gives you a String.

So let's look at the String API. http://www.google.com/search?q=java+string+api

The method I'd take a look at:

indexOf(String str)

Upvotes: 0

Related Questions