Home > Java > javaTutorial > body text

Console input using character streams

Linda Hamilton
Release: 2024-11-11 18:50:03
Original
565 people have browsed it

Entrada do console com o uso de fluxos de caracteres

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);

Copy after login

Then pass this InputStreamReader to the BufferedReader constructor:

BufferedReader br = new BufferedReader(fluxoEntrada);

Copy after login

This way, br is a character-based input stream connected to the console.

Methods for reading characters and strings

  • read(): Reads a single Unicode character and returns -1 at the end of the stream.
  • readLine(): Reads a complete line as a String until the user presses ENTER, returning null at the end of the stream.

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 != '.');

Copy after login

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"));

Copy after login

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template