Using The Scanner Class

Need to scan a .txt file for a certain line of text, and if the text is contained in the file to output the number of times it occurs and the line of actual text in two seperate jtextfields. 

Solution:

You can easily use the Scanner class to do this. I have wrote a quick example for you.

For the purpose of this example I have created a file called data.txt which contains:

hello this is a test
this is a test
this is a test program
my name is monkey
javaprogramming
hello java
test test test test
javaprogramming
test test test test
test test test test
test test test test  

The line we are looking for in the data file is 'javaprogramming' 

The code to do this is here:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Redvenice {

    /**
     * javaprogramming
     */

    // line in data file to find
    public static String findMe = "javaprogramming";
    public static int count = 0;

    public static void main(String[] args) {
        readFile();
    }

    public static void readFile() {

        // Location of file to read
        File file = new File("data.txt");

        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                // System.out.println(line);
                if (line.equals(findMe)) {
                    // increase number of times found
                    count++;
                    // update jtextfields here
                    System.out.println("FOUND - " + line);
                }
            }
            System.out.println(findMe + " found " + count + " times");
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}
 
 

The output is this:

FOUND - javaprogramming
FOUND - javaprogramming
javaprogramming found 2 times  

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.