I am looking for easiest way to read a line in Java. Once read, I want to tokenize the line. Any suggestions?
Asked
Active
Viewed 1,650 times
0
-
Read it from where? Scan it for what? – bmargulies Apr 04 '10 at 12:48
-
like this:http://java.sun.com/javase/6/docs/api/java/util/StringTokenizer.html – jjj Apr 04 '10 at 12:52
-
1Don't use `StringTokenizer`; `Scanner` is now preferred. – polygenelubricants Apr 04 '10 at 12:52
2 Answers
6
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:

Community
- 1
- 1

polygenelubricants
- 376,812
- 128
- 561
- 623
-
-
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