开发者

Read a line in java and then tokenize it

开发者 https://www.devze.com 2022-12-26 04:05 出处:网络
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.*;

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, 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:

  • 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消