0

I am looking for easiest way to read a line in Java. Once read, I want to tokenize the line. Any suggestions?

Oak Bytes
  • 4,489
  • 4
  • 34
  • 52
Ali_IT
  • 7,091
  • 8
  • 27
  • 42

2 Answers2

6
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:

Community
  • 1
  • 1
polygenelubricants
  • 364,035
  • 124
  • 554
  • 617
  • Is Scanner better than BufferedReader? – TBH Apr 04 '10 at 13:16
  • 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 Apr 04 '10 at 13:28
2

FileUtils.readLines(..) from commons-io

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

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132