To read console data in Java efficiently and in a character-friendly way (ideal for internationalization), it is recommended to use character streams instead of byte streams. Since System.in is a stream of bytes, it must be encapsulated in a Reader. The recommended class for this task is BufferedReader, which uses InputStreamReader to convert bytes to characters.
The process works as follows:
Create an InputStreamReader associated with System.in:
InputStreamReader fluxoEntrada = new InputStreamReader(System.in);
Then pass this InputStreamReader to the BufferedReader constructor:
BufferedReader br = new BufferedReader(fluxoEntrada);
This way, br is a character-based input stream connected to the console.
Methods for reading characters and strings
Example of use:
The following code reads characters from the console up to the character . be typed:
char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters, period to quit."); do { c = (char) br.read(); System.out.println(c); } while(c != '.');
Another example allows you to read lines of text until the word "stop" is inserted:
String str; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop"));
These approaches make keyboard data entry more convenient and structured, especially for programs that require support for different character encodings.
The above is the detailed content of Console input using character streams. For more information, please follow other related articles on the PHP Chinese website!