Skip to content
Advertisement

Java how to read stdin?

I need to read the input that is piped to my java program. This is a simple task but I couldn’t find it on the net.

This is what I tried:

private static String getInput() throws IOException {
  StringBuilder sb = new StringBuilder();
  BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  String line;
  while ((line = reader.readLine()) != null) {
    sb.append(line);
  }

  return sb.toString();
}

First of all, is there a simpler way to do it (in java 11, or maybe with a library)? It seems like a lot of lines for such a simple task.

And mostly, it seems that it doesn’t work if there is no piped input, it hangs, when I just want it to return null for example.

Answer

Since Java 8, you can read all lines into a String<Stream>:

private static String getInput() {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    return reader.lines().collect(Collectors.joining("n"));
}

If you want to keep the newlines, you can use an overload for Collectors.joining(), like Collectors.joining("n")

The problem with interactive input is: You may not know if there is an other line coming. So you have to signal end-of-file using your operating system input.
On windows this is the sequence Ctrl+Z, while on Linux it’s Ctrl+D

Advertisement