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,649
  • 4
  • 36
  • 53
Ali_IT
  • 7,551
  • 8
  • 28
  • 44

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
  • 376,812
  • 128
  • 561
  • 623
  • 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
  • 588,226
  • 146
  • 1,060
  • 1,140