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:

JavaScript

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.

Advertisement

Answer

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

JavaScript

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement