Java – is there a simple way to loop stdin in guava?
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 }
Do guava have any similarities?
Solution
Well, first of all... This is not something you particularly need a library, because it only uses the direct 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(); }
But if you want more of it – y guava offers list < string > charstreams readLines(Readable).
I don't think we provide iterators because there is no good way to deal with the existence of ioexceptions Apache's lineiterator seems to silently catch ioexceptions and turn off iterators, but... This seems a confusing, risky and not always the right approach Basically, I think the "guava method" here is to either read the whole input into the list < string > all at once, or make a BufferedReader style loop and decide how to deal with the potential existence of ioexceptions
In general, most of guava's I / O utilities focus on streams that can be closed and reopened, such as files and resources, but unlike system in.