In Apache Commons, I can write:
LineIterator it = IOUtils.lineIterator(System.in, "utf-8");
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
Is there anything similar in Guava?
Scanner sc = new Scanner(System.in,"UTF-8");
while(sc.hasNext()) {
String next = sc.nextLine();
}
You don't need guava for this
Well, to start with...this isn't something you particularly need a library for, given that it's doable with just the straight JDK as
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();
}
but if you want it to be more collections-y Guava provides List<String> CharStreams.readLines(Readable)
.
I think we don't provide an Iterator
because there isn't really any good way to deal with the presence of IOException
s. Apache's LineIterator
appears to silently catch an IOException
and close the iterator out, but...that seems like a confusing, risky, and not always correct approach. Basically, I think the "Guava approach" here is either to either read the whole input into a List<String>
all at once, or to do the BufferedReader
-style loop yourself and decide how you want to deal with the potential presence of IOException
s.
Most of Guava's I/O utilities, in general, are focused on streams that can be closed and reopened, like files and resources, but not really like System.in
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With