The Character Streams
While
the byte stream classes provide sufficient functionality to handle any type of
I/O operation, they cannot work directly with Unicode characters. Since one of
the main purposes of Java is to support the "write once, run
anywhere" philosophy, it was necessary to include direct I/O support for
characters. In this section, several of the character I/O classes are
discussed. As explained earlier, at the top of the character stream hierarchies
are the Reader and Writer abstract classes. We will begin
with them.
Reader
Reader is an abstract class that defines Java’s model
of streaming character input. It implements
the AutoCloseable, Closeable, and Readable interfaces. All of the methods in this class (except for markSupported( )) will throw an IOException on error conditions. Table
20-3 provides a synopsis of the methods in Reader.
Writer
Writer is an abstract class that defines streaming character output. It implements the AutoCloseable, Closeable, Flushable, and Appendable interfaces. All of the methods in this class throw an IOException in the case of errors. Table 20-4 shows a synopsis of the methods in Writer.
FileReader
The FileReader class creates a Reader that you can use to read the
contents of a file. Two commonly used constructors are shown here:
FileReader(String
filePath) FileReader(File fileObj)
Either
can throw a FileNotFoundException.
Here, filePath is the full path name
of a file, and fileObj is a File object that describes the file.
The
following example shows how to read lines from a file and display them on the
standard output device. It reads its own source file, which must be in the
current directory.
//Demonstrate FileReader.
//This program uses try-with-resources. It
requires JDK 7 or later.
import java.io.*;
class FileReaderDemo {
public static void
main(String args[]) {
try ( FileReader fr = new
FileReader("FileReaderDemo.java") )
{
int c;
// Read and display the file.
while((c = fr.read()) != -1)
System.out.print((char) c);
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
FileWriter
FileWriter creates a
Writer that you can use to write to a file. Four commonly used constructors are shown here:
FileWriter(String
filePath)
FileWriter(String
filePath, boolean append) FileWriter(File fileObj)
FileWriter(File
fileObj, boolean append)
They can
all throw an IOException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file.
Creation
of a FileWriter is not dependent on
the file already existing. FileWriter
will create the file before opening it for output when you create the object.
In the case where you attempt to open a read-only file, an IOException will be thrown.
The
following example is a character stream version of an example shown earlier
when FileOutputStream was discussed.
This version creates a sample buffer of characters by first making a String and
then using the getChars( ) method to
extract the character array equivalent. It then creates three files. The first,
file1.txt, will contain every other
character from the sample. The second, file2.txt,
will contain the entire set of characters. Finally, the third, file3.txt, will contain only the last
quarter.
Demonstrate FileWriter.
//This program uses try-with-resources. It
requires JDK 7 or later.
import java.io.*;
class FileWriterDemo {
public static void main(String
args[]) throws IOException { String source = "Now is the time for all good
men\n"
" to come to the aid of their
country\n"
" and pay their due taxes.";
char buffer[] = new
char[source.length()]; source.getChars(0, source.length(), buffer, 0);
try ( FileWriter f0 = new
FileWriter("file1.txt"); FileWriter f1 = new
FileWriter("file2.txt");
FileWriter f2 = new
FileWriter("file3.txt") )
{
// write to first file
for (int i=0; i <
buffer.length; i += 2) { f0.write(buffer[i]);
}
//write to second file
f1.write(buffer);
//write to third file
f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
} catch(IOException e) {
System.out.println("An I/O Error Occurred");
}
}
}
CharArrayReader
CharArrayReader is an implementation of an
input stream that uses a character array as the source. This class has two constructors, each of which requires a
character array to provide the data source:
CharArrayReader(char
array [ ]) CharArrayReader(char array [ ], int start, int numChars)
Here, array is the input source. The second
constructor creates a Reader from a
subset of your character array that begins with the character at the index
specified by start and is numChars long.
The close( ) method implemented by CharArrayReader does not throw any
exceptions. This is because it cannot fail.
The
following example uses a pair of CharArrayReaders:
//Demonstrate CharArrayReader.
//This program uses try-with-resources. It
requires JDK 7 or later.
import java.io.*;
public class
CharArrayReaderDemo {
public static void
main(String args[]) {
String tmp =
"abcdefghijklmnopqrstuvwxyz"; int length = tmp.length();
char c[] = new char[length];
tmp.getChars(0, length, c,
0); int i;
try (CharArrayReader input1 =
new CharArrayReader(c) )
{
System.out.println("input1
is:"); while((i = input1.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
try ( CharArrayReader input2
= new CharArrayReader(c, 0, 5) )
{
System.out.println("input2
is:"); while((i = input2.read()) != -1) {
System.out.print((char)i);
}
System.out.println();
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
The input1 object is constructed using the
entire lowercase alphabet, whereas input2
contains only the first five letters. Here is the output:
input1 is:
abcdefghijklmnopqrstuvwxyz input2 is:
abcde
CharArrayWriter
CharArrayWriter is an implementation of an output
stream that uses an array as the destination.
CharArrayWriter has two
constructors, shown here:
CharArrayWriter(
) CharArrayWriter(int numChars)
In the
first form, a buffer with a default size is created. In the second, a buffer is
created with a size equal to that specified by numChars. The buffer is held in the buf field of CharArrayWriter.
The buffer size will be increased automatically, if needed. The number of characters held by the buffer is
contained in the count field of CharArrayWriter. Both buf and count are protected fields.
The close( ) method has no effect on a CharArrayWriter.
The
following example demonstrates CharArrayWriter
by reworking the sample program shown earlier for ByteArrayOutputStream. It produces the same output as the previous
version.
class BufferedReaderDemo {
public static void
main(String args[]) throws IOException { String s = "This is a ©
copyright symbol " +
"but this is ©
not.\n"; char buf[] = new char[s.length()]; s.getChars(0, s.length(), buf,
0);
CharArrayReader in = new
CharArrayReader(buf); int c;
boolean marked = false;
try ( BufferedReader f = new
BufferedReader(in) )
{
while ((c = f.read()) != -1)
{ switch(c) {
case '&':
if (!marked) { f.mark(32);
marked = true;
} else {
marked = false;
}
break; case ';':
if (marked) { marked = false;
System.out.print("(c)");
} else
System.out.print((char) c);
break; case ' ':
if (marked) { marked = false;
f.reset();
System.out.print("&");
} else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}
}
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
BufferedWriter
A BufferedWriter is a Writer that buffers output. Using a BufferedWriter can improve performance
by reducing the number of times data is actually physically written to the
output device.
A BufferedWriter has these two
constructors:
BufferedWriter(Writer
outputStream) BufferedWriter(Writer outputStream, int bufSize)
The
first form creates a buffered stream using a buffer with a default size. In the
second, the size of the buffer is passed in bufSize.
PushbackReader
The PushbackReader class allows one or more
characters to be returned to the input stream. This allows you to look ahead in
the input stream. Here are its two constructors:
PushbackReader(Reader
inputStream) PushbackReader(Reader inputStream, int bufSize)
The
first form creates a buffered stream that allows one character to be pushed
back. In the second, the size of the pushback buffer is passed in bufSize.
Closing
a PushbackReader also closes the
underlying stream specified by inputStream.
PushbackReader provides unread( ), which returns one or more
characters to the invoking input stream. It has the three forms shown here:
void
unread(int ch) throws IOException
void
unread(char buffer [ ]) throws
IOException
void
unread(char buffer [ ], int offset, int numChars) throws IOException
The
first form pushes back the character passed in ch. This will be the next character returned by a subsequent call
to read( ). The second form returns
the characters in buffer. The third
form pushes back numChars characters
beginning at offset from buffer. An IOException will be thrown if there is an attempt to return a character
when the pushback buffer is full.
The
following program reworks the earlier PushbackInputStream
example by replacing PushbackInputStream
with PushbackReader. As before,
it shows how a programming language
parser can use a pushback stream to deal with the difference between the == operator for comparison and the = operator for assignment.
//Demonstrate unread().
//This program uses try-with-resources. It
requires JDK 7 or later.
import java.io.*;
class PushbackReaderDemo {
public static void main(String
args[]) { String s = "if (a == 4) a = 0;\n"; char buf[] = new
char[s.length()]; s.getChars(0, s.length(), buf, 0);
CharArrayReader in = new
CharArrayReader(buf); int c;
try ( PushbackReader f = new
PushbackReader(in) )
{
while ((c = f.read()) != -1)
{ switch(c) {
case '=':
if ((c = f.read()) == '=')
System.out.print(".eq.");
else {
System.out.print("<-"); f.unread(c);
}
break;
default:
System.out.print((char) c); break;
}
}
} catch(IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
PrintWriter
PrintWriter is essentially a character-oriented version of PrintStream. It implements the
Appendable,
AutoCloseable, Closeable, and Flushable interfaces. PrintWriter has several constructors. The following have been
supplied by PrintWriter from the
start:
PrintWriter(OutputStream
outputStream)
PrintWriter(OutputStream outputStream,
boolean autoFlushingOn)
PrintWriter(Writer outputStream)
PrintWriter(Writer
outputStream, boolean autoFlushingOn)
Here, outputStream specifies an open OutputStream that will receive output.
The autoFlushingOn parameter controls
whether the output buffer is automatically flushed every time println( ), printf( ), or format( ) is called. If autoFlushingOn
is true, flushing automatically
takes place. If false, flushing is
not automatic. Constructors that do not specify the autoFlushingOn parameter do not automatically flush.
The next
set of constructors gives you an easy way to construct a PrintWriter that writes its output to a file.
PrintWriter(File
outputFile) throws
FileNotFoundException PrintWriter(File outputFile,
String charSet)
throws
FileNotFoundException, UnsupportedEncodingException PrintWriter(String outputFileName) throws
FileNotFoundException PrintWriter(String outputFileName,
String charSet)
throws
FileNotFoundException, UnsupportedEncodingException
These
allow a PrintWriter to be created
from a File object or by specifying
the name of a file. In either case, the file is automatically created. Any
preexisting file by the same name is destroyed.
Once
created, the PrintWriter object directs all output to the specified file. You
can specify a character encoding by passing its name in charSet.
PrintWriter supports the print( ) and println( ) methods
for all types, including Object. If an argument is not a primitive
type, the PrintWriter methods will
call the object’s toString( ) method
and then output the result.
PrintWriter also supports the printf( ) method. It works the same way it does in the PrintStream class described earlier:
It allows you to specify the precise format of the data. Here is how printf( )
is declared in PrintWriter:
PrintWriter
printf(String fmtString, Object … args)
PrintWriter
printf(Locale loc, String fmtString, Object …args)
The
first version writes args to standard
output in the format specified by fmtString,
using the default locale. The second lets you specify a locale. Both return the
invoking
PrintWriter.
The format( ) method is also supported. It
has these general forms:
PrintWriter
format(String fmtString, Object … args)
PrintWriter
format(Locale loc, String fmtString, Object … args)
It works
exactly like printf( ).
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.