see Reader class for descriptions of the methods FileReader uses. They are:
.mark( readAheadLimit ) Mark the present position in the stream.
.markSupported( ) Tell whether this stream supports the mark(...) operation.
.read( ) Read a single character, returning it in the low end two bytes of an int.
.read( char[ ] ) Read characters into a char array.
.read( char[ ], offset, len) Read characters into a portion of a char array.
.ready( ) Tell whether this stream is ready to be read.
.reset( ) Reset the stream.
.skip( n ) Skip over n characters in the stream.
.close( ) Close the stream.
■ FileReader is a class for directly reading files containing text which is default Unicode characters. Because ASCII parallels the default UTF-8 encoding, it can also read ASCII text files.
■ FileReader extends InputStreamReader, from Reader, so all nine Reader methods are available. FileReader adds no additional methods.
See Reader class for the methods.
■ FileReader's constructors accept either a String of the source filename or a File object representing it. i.e. The three variations shown below all work:
File
f = new File( "mycharfile" );
FileReader
fr = new FileReader( f );
FileReader
fr = new FileReader( new File( "mycharfile" ));
FileReader
fr = new FileReader( "mycharfile" );
■ You cannot use mark( ) or reset( ) with FileReader as they are not supported for this stream.
■ You cannot correctly read the contents of non-UTF-16 files with FileReader. That's because you cannot change Java's Unicode's UTF-16 default character encoding using FileReader's constructors. These constructors do not have a provision for specifying the CharSet of the input file. To specify another CharSet yourself, so that you can correctly read the characters of a non-UTF-16 file, chain an InputStreamReader which specifies the necessary CharSet to a FileInputStream. See InputStreamReader class for an example.
■ The FileReader snippet below simply
reads and prints the contents of a character file. Note the printing will be
distorted, as it will show both 8-bit halves of each 16-bit character. The beginning fr declaration statement
is outside the try block for scope purposes, so that the object
handle fr can be referenced later by the fr.close(
); statement.
FileReader
fr = null;
try {
fr = new FileReader( new File(
"mycharfile" ));
int c;
while (( c = fr.read( )) != -1 ) {
System.out.print( String.valueOf(
(char) c) );
}
}
catch
(IOException ex) { }
finally
{
try {
if ( fr != null ) {
fr.close( );
}
} catch (IOException ex) { }
}
■ Here is a FileReader sample program which reads and counts the characters in a
file. It rethrows IOException and thus contains no try-catch I/O error checking.
import
java.io.*;
public
class FileReaderDemo {
public static void main( String[ ] args )
throws IOException {
FileReader fr = new FileReader(
"mycharfile" );
int x = 0;
while ( fr.read( ) != -1 ) {
x++;
}
System.out.println( "The file
contains " + x + "characters." );
}
}