Read a line in java and then tokenize it
I am looking for easiest way to read a li开发者_Python百科ne in Java. Once read, I want to tokenize the line. Any suggestions?
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, andStringas 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:
- Java’s Scanner vs String.split() vs StringTokenizer; which should I use?
 - How to read integer value from the standard input in Java
 - How do I keep a scanner from throwing exceptions when the wrong type is entered?
 
FileUtils.readLines(..) from commons-io
Then use String.split(regex) rather than a tokenizer.
 加载中,请稍侯......
      
精彩评论