How to search for a particular string in a text file using java?

Using a String Tokenizer in java with File I/O?

  • I'm trying to use a StringTokenizer to read from a file and get the information from it. There's a set a names and then a set of numbers. Each name has 5 numbers attached to it. Ex: Johnson 50 60 70 80 90 Frank 60 65 70 75 80 I need to have the names attached to one array and the numbers to another. This is what I have so far and it's just giving me an error: File inputData = new File("C://CS161//Data.txt"); Scanner Data = new Scanner(inputData); input = Data.next(); StringTokenizer tokens = new StringTokenizer(input); String name = tokens.nextToken(); String number = tokens.nextToken(); If I try to use more than one .nextToken() it gives me an error. Why is this?

  • Answer:

    You can't mix StringBuffer with Scanner. Scanner is the more flexible. int i; double d; boolean b; String str; FileReader fin = new FileReader("Test.txt"); Scanner src = new Scanner(fin); while (src.hasNext()) { if (src.hasNextInt()) { i = src.nextInt(); System.out.println("int: " + i); } else if (src.hasNextDouble()) { d = src.nextDouble(); System.out.println("double: " + d); } else if (src.hasNextBoolean()) { b = src.nextBoolean(); System.out.println("boolean: " + b); } else { str = src.next(); System.out.println("String: " + str); } // make a new Object, whatever with your tokens } fin.close(); }

Rhendar at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

I believe your problem lies in the line where you call Data.next(). The next() function of a Scanner will get the next string up until a whitespace character. Thus, you are essentially retrieving only one token from the file. When you try to extract more than one token from such a string (with only one token), you will get an error. --- EDIT: If you want a fix, I would suggest simply calling Data.next() for each new "token" you want to retrieve rather than trying to deal with StringTokenizer. It will probably be much simpler.

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.