Search code examples
javadatainputstream

Java DataInputStream usage with System.in


A simple programm

    DataInputStream in = new DataInputStream(System.in);
    while(true)
        System.out.println(in.readUTF());

Behaves somewhat weird: it refuses to output the inputed text... I use terminal to input some text into it, but there's nothing in the output. What's wrong with it?


Solution

  • It's not weird at all. readUTF expects a very specific length-prefixed format as written by DataOutputStream. That's not what your terminal will be providing. See the documentation in DataInput.readUTF for more details.

    You should generally just use a Scanner or create an InputStreamReader around System.in, and a BufferedReader around that, and use BufferedReader.readLine().