Re: InputStreamReader question
In article <7ee3b$4661ee98$54704fad$13346@news.chello.at>, Sam Petrosa says...
Hi,
I am stuck in a problem.
The following code doesn't quit the for/while loop:
It worked fine for me, see below.
InputStreamReader ins = new InputStreamReader(System.in);
StringBuilder sb = new StringBuilder();
for(int c = ins.read(); c != -1; c = ins.read()) {
sb.append((char)c);
}
or
InputStreamReader ins = new InputStreamReader(System.in);
StringBuilder sb = new StringBuilder();
while((c = ins.read()) != -1) {
sb.append((char)c);
}
can somebody please help me understand it?
I guess it all boils down to the question
when does read() return -1?
That is exactly right. It does boil down to that. The API spec does not say when
the platforms System.in is required to return -1 in the read() method. And in
WinXP, as long as you are reading from the keyboard (standard in), it will never
return -1. But if you are reading from a file, it will work just fine; once it
reaches the end of the file, read() will return -1.
For example, I wrapped your code with a class called ISRex, put text in 'infile'
and ran it like this: "java.exe ISRex <infile". It worked perfectly.
But when running with the keyboard as standard input, I could not get it to
return -1, not even by entering ^D.