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();
//...
}
- It can take a
File
,InputStream
, andString
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
2010-04-04 12:46:55
Is Scanner better than BufferedReader?
TBH
2010-04-04 13:16:28
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
2010-04-04 13:28:58
+1
A:
FileUtils.readLines(..)
from commons-io
Then use String.split(regex)
rather than a tokenizer.
Bozho
2010-04-04 13:03:25