在 Apache Commons 中,我可以写:
LineIterator it = IOUtils.lineIterator(System.in, "utf-8");
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
Guava有没有类似的东西?
最佳答案
好吧,首先......这不是你特别需要一个库的东西,因为它可以用直接的 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();
}
但是如果你想让它成为更多的 Collection 品-y Guava 提供了 List<String> CharStreams.readLines(Readable)
.
我认为我们不提供 Iterator
因为实际上没有任何好的方法来处理 IOException
的存在秒。 Apache 的 LineIterator
似乎默默地捕获了一个IOException
并关闭迭代器,但是......这似乎是一种令人困惑、冒险且并不总是正确的方法。基本上,我认为这里的“ Guava 方法”要么将整个输入读入 List<String>
一次全部,或者做BufferedReader
-style loop yourself and decide how you to deal with potential presence of IOException
大多数 Guava 的 I/O 实用程序,一般来说,都集中在可以关闭和重新打开的流上,比如文件和资源,但不像 System.in
。 .
关于java - 有没有一种简单的方法可以在 Guava 中循环标准输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811194/