Question

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?

Was it helpful?

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

OTHER TIPS

DataInputStream is for reading binary data. readUTF expects a two byte unsigned length followed by the characters in UTF-8. (If you are intreested you can read it's documentation hint, hint)

I suspect what you intended to use was Scanner which is designed to read text.

Scanner in = new Scanner(System.in);
while(in.hasNextLine())
    System.out.println(in.nextLine());

Can you try like

String str;
while((str = in.readUTF()) != null) {
     System.out.println(str);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top