有没有简单的方法来循环在番石榴的stdin?
问题描述:
在阿帕奇百科全书,我可以这样写:有没有简单的方法来循环在番石榴的stdin?
LineIterator it = IOUtils.lineIterator(System.in, "utf-8");
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
有什么番石榴相似?
答
好了,开始用......这是不是你特别需要一个图书馆,因为它是可行的只有直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 Guava提供List<String> CharStreams.readLines(Readable)
。
我认为我们不提供Iterator
,因为没有什么好办法来处理IOException
的存在。 Apache的LineIterator
似乎默默地捕获了IOException
并关闭了迭代器,但是......似乎是一种令人困惑,有风险但并不总是正确的方法。基本上,我认为这里的“番石榴方法”要么一次读取全部输入到List<String>
,要么自己完成BufferedReader
式循环,并决定如何想要处理IOException
的潜在存在。
大多数番石榴的I/O工具通常集中在可以关闭和重新打开的文件和资源之类的流上,但并不像System.in
。
答
Scanner sc = new Scanner(System.in,"UTF-8");
while(sc.hasNext()) {
String next = sc.nextLine();
}
你不需要番石榴此
答
由于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
})
如果你真的想如果没有番石榴,那么你可以使用['StandardCharsets.UTF_8'](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8) 7.但是,对UTF-8进行硬编码可能不是最好的主意(除非你主要接受明确的输入作为反对)编辑用户在stdin上的交互)。 –
哦,所以他们在Java 7中添加了它。把它们花了足够长的时间。 –
是的,有人拿了几个提示;-) –