Ali_IT
Ali_IT

Reputation: 8279

Read a line in java and then tokenize it

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

Upvotes: 0

Views: 1747

Answers (2)

Bozho
Bozho

Reputation: 597076

FileUtils.readLines(..) from commons-io

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

Upvotes: 2

polygenelubricants
polygenelubricants

Reputation: 383746

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:

Upvotes: 6

Related Questions