Java Reference
In-Depth Information
10.1.2
The classes
FileReader
and
FileWriter
The classes
FileReader
and
FileWriter
supply methods for reading and writing
ASCII files. These are
convenience classes
as they make it easy to access files.
The programmer does not have to define a stream explicitly. We start by looking
at a constructor and some methods of class
FileReader
:
FileReader(File aFile)
void
close()
int
read()
int
read(
char
[] buffer,
int
start,
int
length)
FileReader(File aFile)
opens the file
aFile
for reading. All further methods
refer to this file.
close()
stops the file reader and closes the file. It is important not to forget this
!
command, otherwise the file might not be accessible by other applications.
read()
reads a single character from the file and returns its integer value (ASCII
code).
read(buffer,start,length)
reads
length
and puts the characters into the
char
-array
buffer
starting at position
start
of the buffer. Returns the number
of characters read or
−
1ifthe file end is reached.
Most constructors and methods of
java.io
throw exceptions if errors occur,
!
mostly
IOException
s. Thus they have to be embedded into
try-catch
blocks
or the exceptions have to be thrown further.
Class
FileWriter
supplies methods for writing an ASCII file:
FileWriter(File aFile)
void
close()
void
write(
char
[] buffer)
void
write(
char
[] buffer,
int
start,
int
length)
void
write(String str,
int
start,
int
length)
FileWriter(File aFile)
- this constructor opens the file
aFile
for writing. If
!
the file is already present the old content is lost! All further methods refer to
this file.
close()
stops the file writer and closes the file. It is important not to forget this
!
command, otherwise part of the data might not be written.
write(char[] buffer)
writes the content of the buffer to the file by appending
it to the previously written text.
write(buffer,start,length)
writes the number of characters equivalent to the
current value of
length
from
buffer
starting at position
start
of the buffer.
The text is appended to the previously written text.
Search WWH ::
Custom Search