itsadok itsadok - 1 year ago 76
Java Question

Is there a simple way to loop over stdin in Guava?

In Apache Commons, I can write:

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

Is there anything similar in Guava?

Answer Source

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(,
// 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 IOExceptions. 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 IOExceptions.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download