Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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
}

Is there anything similar in Guava?

like image 989
itsadok Avatar asked Nov 30 '22 06:11

itsadok


2 Answers

Scanner sc = new Scanner(System.in,"UTF-8");
while(sc.hasNext()) {
  String next = sc.nextLine();
}

You don't need guava for this

like image 39
Emily Avatar answered Dec 22 '22 11:12

Emily


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 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.

like image 156
Louis Wasserman Avatar answered Dec 22 '22 10:12

Louis Wasserman