To perform character-based I/O operations, Java provides its own hierarchy of character-based streams, with abstract classes such as Reader and Writer. These classes allow you to read and write characters directly, making them more suitable for text data than byte streams. The main methods of these classes handle read and write operations and can throw IOException in case of an error.
Character Flow Structure
Main Abstract Classes:
These classes form the minimal structure of I/O operations for character streams, with methods applicable to all subclasses.
Console Input with Character Streams
For internationalized programs or programs that manipulate text, it is preferable to read characters from the console using character streams. Since System.in is a byte stream, it needs to be adapted for character streams.
For this, we use:
Example of Reading Console Input
To read console input with BufferedReader, we first convert System.in to a character stream using InputStreamReader:
import java.io.*; public class ConsoleReaderExample { public static void main(String args[]) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.print("Digite uma linha de texto: "); String linha = reader.readLine(); System.out.println("Você digitou: " + linha); } catch(IOException e) { System.out.println("Erro de entrada/saída: " + e); } } }
Code Explanation
Advantages of Character Flows
These character streams make text processing easier and are ideal for data entry and file manipulation where characters and text are the main focus.
The above is the detailed content of Using the Java language character-based streams. For more information, please follow other related articles on the PHP Chinese website!