The Java platform stores character values using Unicode conventions. Character stream I/O automatically translates this internal format to and from the local character set. In Western locales, the local character set is usually an 8-bit superset of ASCII.
For most applications, I/O with character streams is no more complicated than I/O with byte streams. Input and output done with stream classes automatically translates to and from the local character set. A program that uses character streams in place of byte streams automatically adapts to the local character set and is ready for internationalization — all without extra effort by the programmer.
If internationalization isn't a priority, you can simply use the character stream classes without paying much attention to character set issues. Later, if internationalization becomes a priority, your program can be adapted without extensive recoding. See the Internationalization trail for more information.
Using Character Streams
All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. The CopyCharacters example illustrates these classes.
public class CopyCharacters {
public static void main(String[] args) throws IOException {
code
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
CopyCharacters is very similar to CopyBytes. The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream. Notice that both CopyBytes and CopyCharacters use an int variable to read to and write from. However, in CopyCharacters, the int variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a byte value in its last 8 bits.
Character Streams that Use Byte Streams
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
Assistant
There are two general-purpose byte-to-character "bridge" streams: InputStreamReader and OutputStreamWriter. Use them to create character streams when there are no prepackaged character stream classes that meet your needs. The sockets lesson in the networking trail shows how to create character streams from the byte streams provided by socket classes.
Line-Oriented I/O
Character I/O usually occurs in bigger units than single characters. One common unit is the line: a string of characters with a line terminator at the end. A line terminator can be a carriage-return/line-feed sequence ("\r\n"), a single carriage-return ("\r"), or a single line-feed ("\n"). Supporting all possible line terminators allows programs to read text files created on any of the widely used operating systems.
Let's modify the CopyCharacters example to use line-oriented I/O. To do this, we have to use two classes we haven't seen before, BufferedReader and PrintWriter. We'll explore these classes in greater depth in Buffered I/O and Formatting. Right now, we're just interested in their support for line-oriented I/O.
The CopyLines example invokes BufferedReader.readLine and PrintWriter.println to do input and output one line at a time.
public class CopyLines {
public static void main(String[] args) throws IOException {
code
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
Invoking readLine returns a line of text with the line. CopyLines outputs each line using println, which appends the line terminator for the current operating system. This might not be the same line terminator that was used in the input file.
There are many ways to structure text input and output beyond characters and lines. For more information, see Scanning and Formatting.
Sure! Let's delve into Character Streams in Java, exploring how they work, their advantages, and how to effectively use them in your applications. We'll break down the concepts, examine example code, and highlight best practices.
1. Introduction to Character Streams
What Are Character Streams?
Character streams in Java are designed to handle input and output (I/O) of data in the form of characters. They are part of Java’s I/O (Input/Output) system, which allows programs to read data from sources (like files or user input) and write data to destinations (like files or the console).
Why Use Character Streams?
Unicode Support: Java uses Unicode to represent characters, allowing for consistent handling of international characters across different platforms and locales.
Automatic Translation: Character streams automatically handle the conversion between Unicode and the local character set (like UTF-8, ISO-8859-1, etc.), simplifying the development of international applications.
Ease of Use: For text-based I/O, character streams are generally easier to use compared to byte streams, as they work directly with characters rather than raw bytes.
2. Byte Streams vs. Character Streams
Byte Streams (InputStream and OutputStream):
Purpose: Handle I/O of raw binary data (bytes).
Use Cases: Reading/writing binary files (images, audio, etc.), network communications.
Classes:FileInputStream, FileOutputStream, etc.
Character Streams (Reader and Writer):
Purpose: Handle I/O of character data (text).
Use Cases: Reading/writing text files, processing textual data.
Classes:FileReader, FileWriter, BufferedReader, PrintWriter, etc.
Key Difference:
Byte Streams deal with raw binary data and are suitable for all types of I/O, including binary files.
Character Streams are specialized for text data and provide additional functionality like character encoding translation.
3. Core Classes of Character Streams
All character stream classes in Java inherit from two main abstract classes:
Reader: The abstract class for reading character streams.
Writer: The abstract class for writing character streams.
Specialized Classes for File I/O:
FileReader: A convenience class for reading character files. It uses the default character encoding.
FileWriter: A convenience class for writing character files. It uses the default character encoding.
4. Working with Character Streams
4.1. Copying Characters with FileReader and FileWriter
Let's examine the CopyCharacters example to understand how to use FileReader and FileWriter.
Example Code: CopyCharacters
java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("characteroutput.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
Explanation:
Import Statements:
FileReader and FileWriter classes are imported to handle file-based character I/O.
IOException is imported to handle I/O-related exceptions.
Setting Up Streams:
FileReader inputStream: Reads characters from xanadu.txt.
FileWriter outputStream: Writes characters to characteroutput.txt.
Reading and Writing Characters:
The program reads one character at a time from the input file using inputStream.read().
Each character is then written to the output file using outputStream.write(c).
The loop continues until read() returns -1, indicating the end of the file.
Closing Streams:
In the finally block, both the input and output streams are closed to release system resources, ensuring they are closed even if an exception occurs.
Key Points:
Using int for Characters: Although characters are 16 bits in Unicode, methods like read() return an int to accommodate the -1 end-of-file indicator.
Resource Management: Always close streams in a finally block (or use try-with-resources in modern Java) to prevent resource leaks.
4.2. Wrapping Character Streams Around Byte Streams
Character streams can be built on top of byte streams, acting as "bridges" that handle the conversion between bytes and characters. This is useful when you need more control over the encoding or when dealing with sources that provide byte streams.
Key Bridge Classes:
InputStreamReader: Converts a byte InputStream into a character Reader.
OutputStreamWriter: Converts a byte OutputStream into a character Writer.
Example Usage:
java
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.IOException;
public class BridgeStreamsExample {
public static void main(String[] args) throws IOException {
try (
InputStreamReader reader = new InputStreamReader(new FileInputStream("xanadu.txt"), "UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("characteroutput.txt"), "UTF-8");
) {
int c;
while ((c = reader.read()) != -1) {
writer.write(c);
}
}
}
}
Advantages:
Custom Encoding: Specify the character encoding explicitly (e.g., UTF-8, ISO-8859-1).
Flexibility: Use with any byte-based input or output source, such as network streams or in-memory byte arrays.
4.3. Line-Oriented I/O with BufferedReader and PrintWriter
Handling data line by line is common in text processing. Java provides classes that simplify reading and writing lines of text.
Example Code: CopyLines
java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream = new BufferedReader(new FileReader("xanadu.txt"));
outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
String line;
while ((line = inputStream.readLine()) != null) {
outputStream.println(line);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
Explanation:
Using BufferedReader:
Wraps FileReader to provide buffering and the convenient readLine() method.
readLine() Method: Reads an entire line of text, handling different line terminators (\n, \r, \r\n).
Using PrintWriter:
Wraps FileWriter to provide convenient methods like println() for writing lines.
println() Method: Writes the string followed by a line terminator appropriate to the operating system.
Advantages of Line-Oriented I/O:
Efficiency: Buffered reading reduces the number of I/O operations by reading larger chunks of data at once.
Convenience: Methods like readLine() and println() simplify reading and writing lines compared to handling individual characters.
Resource Management: Utilizes finally to ensure streams are closed properly.
5. Best Practices
5.1. Use Try-With-Resources (Java 7+)
To simplify resource management and ensure streams are closed automatically, use the try-with-resources statement.
Rewriting CopyLines with Try-With-Resources:
java
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public class CopyLines {
public static void main(String[] args) {
try (
BufferedReader inputStream = new BufferedReader(new FileReader("xanadu.txt"));
PrintWriter outputStream = new PrintWriter(new FileWriter("characteroutput.txt"));
) {
String line;
while ((line = inputStream.readLine()) != null) {
outputStream.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Benefits:
Automatic Resource Management: Streams are closed automatically at the end of the try block.
Cleaner Code: Reduces boilerplate finally blocks.
5.2. Specify Character Encoding Explicitly
Relying on the platform’s default encoding can lead to inconsistencies, especially in international applications. Specify the encoding explicitly using InputStreamReader and OutputStreamWriter.
Example:
java
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class CopyLinesWithEncoding {
public static void main(String[] args) {
try (
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(new FileInputStream("xanadu.txt"), StandardCharsets.UTF_8));
PrintWriter outputStream = new PrintWriter(
new OutputStreamWriter(new FileOutputStream("characteroutput.txt"), StandardCharsets.UTF_8));
) {
String line;
while ((line = inputStream.readLine()) != null) {
outputStream.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Advantages:
Consistency: Ensures that data is read and written using the specified encoding, avoiding mismatches.
Internationalization: Proper handling of diverse character sets.
6. Advanced Topics
6.1. Internationalization (i18n) and Localization (l10n)
Character streams facilitate the development of applications that support multiple languages and regions by handling different character sets seamlessly. By relying on Unicode and allowing for explicit encoding, developers can create applications that adapt to various cultural contexts without extensive code changes.
6.2. Buffering for Performance
Using buffered streams like BufferedReader and BufferedWriter can significantly improve I/O performance by reducing the number of read/write operations, especially when dealing with large amounts of data.
6.3. Formatting and Parsing
For more sophisticated text processing, consider using classes like Scanner for parsing and Formatter or PrintWriter for formatted output. These classes provide additional functionality for handling structured text data.
7. Summary
Character Streams (Reader and Writer): Ideal for handling text data with support for Unicode and different character encodings.
Key Classes:
FileReader / FileWriter: Simplified classes for file-based character I/O.
BufferedReader / PrintWriter: Provide efficient, line-oriented I/O methods.
InputStreamReader / OutputStreamWriter: Bridge classes to convert byte streams to character streams with explicit encoding control.
Best Practices:
Use try-with-resources for automatic stream management.
Specify character encoding explicitly to avoid platform-dependent issues.
Leverage buffered streams for improved performance.
Advantages:
Simplifies text-based I/O operations.
Facilitates internationalization without significant code modifications.
By understanding and effectively utilizing Java’s character streams, you can create robust, efficient, and international-friendly applications that handle text data gracefully.
If you have any specific questions or need further examples on any of these topics, feel free to ask!