Take the 2-minute tour ×

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?

share|improve this question
add comment

2 Answers

up vote 7 down vote accepted

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,
// 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 System.in.

share|improve this answer
If you really want to do it without Guava, then you could use StandardCharsets.UTF_8 from Java 7. But hard-coding UTF-8 is probably not the best idea anyway (unless you primarily accept well-specified input as opposed to user interaction on stdin). –  Joachim Sauer May 30 '12 at 7:06
Oh, so they did add that in Java 7. Took them long enough. –  Louis Wasserman May 30 '12 at 7:08
Yes, someone took a few hints ;-) –  Joachim Sauer May 30 '12 at 7:08
Thanks. reader.nextLine should be reader.readLine, though. –  itsadok May 30 '12 at 7:20
add comment
Scanner sc = new Scanner(System.in,"UTF-8");
while(sc.hasNext()) {
  String next = sc.nextLine();

You don't need guava for this

share|improve this answer
add comment

Your Answer


