Character Streams in Java are used to read and write text data (characters). They are designed to handle Unicode characters and are ideal for text-based input and output.
java.io packageCharacter streams use Reader and Writer as abstract base classes. Common implementations include FileReader and FileWriter.
// Writing text to a file using FileWriter
import java.io.FileWriter;
import java.io.IOException;
class WriteExample {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("data.txt");
fw.write("Hello Character Stream");
fw.close();
}
}
// Reading text from a file using FileReader
import java.io.FileReader;
import java.io.IOException;
class ReadExample {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("data.txt");
int ch;
while((ch = fr.read()) != -1) {
System.out.print((char)ch);
}
fr.close();
}
}
The first program writes text into a file. The second program reads the file character by character and prints it on the console.
Simulate how Java writes to a file and reads it back character by character.
BufferedReader for efficiencyBufferedReader