tags:

views:

135

answers:

2

i want the easiest way to read a line in java. after that i want to tokenize it.

+5  A: 
import java.util.*;

//...

Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
if (sc.hasNextInt()) {
  int i = sc.nextInt();
  //...
}

java.util.Scanner API

  • It can take a File, InputStream, and String as source (among other things)
    • new Scanner(new File("input.txt"))
    • new Scanner("some string you want to tokenize")
  • You can also set custom delimiter
    • sc.useDelimiter(";")
  • Supports regex too
    • sc.next("[a-z]+")

Elsewhere on stackoverflow:

polygenelubricants
Is Scanner better than BufferedReader?
TBH
You may want to combine `BufferedReader` with `Scanner` if you insist on reading a line _and then_ tokenizing it, but `Scanner` lets you tokenize a line as you're reading it, so in some cases that simplifies things.
polygenelubricants
+1  A: 

FileUtils.readLines(..) from commons-io

Then use String.split(regex) rather than a tokenizer.

Bozho
Disadvantage of this is that you need a third-party library.
Jesper