Reputation: 346
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?
Upvotes: 0
Views: 1305
Reputation: 11298
Can you try like
String str;
while((str = in.readUTF()) != null) {
System.out.println(str);
}
Upvotes: 0
Reputation: 533492
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());
Upvotes: 2
Reputation: 1500065
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()
.
Upvotes: 3