是否有一种简单的方法可以在Guava中循环stdin?

时间:2012-05-30 06:43:46

标签: java guava

在Apache Commons中,我可以写:

LineIterator it = IOUtils.lineIterator(System.in, "utf-8");
while (it.hasNext()) {
    String line = it.nextLine();
    // do something with line
}

番石榴有什么相似之处吗?

3 个答案:

答案 0 :(得分:9)

嗯,首先......这不是你特别需要一个库的东西,因为它只能用直接的JDK来实现

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in,
  Charsets.UTF_8));
// okay, I guess Charsets.UTF_8 is Guava, but that lets us not worry about
// catching UnsupportedEncodingException
while (reader.ready()) {
  String line = reader.readLine();
}

但是如果你想要它更多的集合 - y番石榴提供List<String> CharStreams.readLines(Readable)

我认为我们没有提供Iterator,因为没有任何好的方法来处理IOException的存在。 Apache的LineIterator似乎默默地捕获IOException并关闭迭代器,但......这似乎是一种令人困惑,冒险且并非总是正确的方法。基本上,我认为这里的“Guava方法”要么是将整个输入一次性读入List<String>,要么自己进行BufferedReader - 样式循环并决定你< / em>想要处理IOException s的潜在存在。

一般来说,Guava的大多数I / O实用程序都专注于可以关闭和重新打开的流,例如文件和资源,但不是真的像System.in

答案 1 :(得分:9)

Scanner sc = new Scanner(System.in,"UTF-8");
while(sc.hasNext()) {
  String next = sc.nextLine();
}

你不需要番石榴

答案 2 :(得分:1)

由于Java 8 BufferedReader有新的方法lines(),它返回一行你可以轻松使用的行:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(System.in, StandardCharsets.UTF_8));
reader.lines()
    .forEach(line -> { // or any other stream operation
      // process liness
    })