Java Uni5
Java Uni5
Java Uni5
InputStreamReader is a bridge from byte streams to character streams. It converts bytes into
characters using a specified charset. The charset can be default character encoding of the
operating system, or can be specified explicitly when creating an InputStreamReader.
FileReader is a convenient class for reading text files using the default character encoding of
the operating system.
BufferedReader reads text from a character stream with efficiency (characters are buffered to
avoid frequently reading from the underlying stream) and provides a convenient method for
reading a line of text readLine().
The following diagram show relationship of these reader classes in the java.io package:
writeris the abstract class for writing character streams. It implements the following
fundamental methods:
OutputStreamWriter is a bridge from byte streams to character streams. Characters are encoded
into bytes using a specified charset. The charset can be default character encoding of the operating
system, or can be specified explicitly when creating an OutputStreamWriter.
FileWriter is a convenient class for writing text files using the default character encoding of the
operating system.
BufferedWriter writes text to a character stream with efficiency (characters, arrays and strings are
buffered to avoid frequently writing to the underlying stream) and provides a convenient method for
writing a line separator: newLine().
That creates a new reader with the Unicode character encoding UTF-16.
And the following statement constructs a writer with the UTF-8 encoding:
1 OutputStreamWriter writer = new OutputStreamWriter(
2 new FileOutputStream("YourFile.txt"), "UTF-8");
In case we want to use a BufferedReader, just wrap the InputStreamReader inside, for example:
1 InputStreamReader reader = new InputStreamReader(
2 new FileInputStream("MyFile.txt"), "UTF-16");
3
4 BufferedReader bufReader = new BufferedReader(reader);
The following small program reads every single character from the
file MyFile.txt and prints all the characters to the output console:
import java.io.FileReader;
import java.io.IOException;
/**
* This program demonstrates how to read characters from a text file.
*/
public class TextFileReadingExample1 {
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* This program demonstrates how to write characters to a text file.
*
*/
public class TextFileWritingExample1 {