A related question is this one: Where is the specification that defines this behavior for InputStreamReader?, but I'm not sure if it answers mine... Please note, I'm just experimenting with the language. I have this code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Capitalize {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(
System.in))) {
char c;
do {
c = Character.toUpperCase((char) br.read());
System.out.print(c);
} while (c != (char) -1);
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
Using ubuntu linux, I was expecting the output to be like this:
fFoOoO bBaArR
but instead, it's like this:
foo bar (line feed)
FOO BAR (waits for more characters or Ctrl + D)
Right now I'm not sure about what is the behavior in windows, probably it's different, but still, this confuses me a bit. Reading the documentation for the read
method, I see it will only return -1 if the end of stream is reached. I kind of understand how that would work for reading a file, but how about, in this case, the console? Why does it have to wait until the Ctrl + D is typed? Is there any way to get to the end of the stream without having to type Ctrl + D? Is there a way to achieve what I was expecting?
Thanks in advance