Java Reference
In-Depth Information
look at some of the more commonly used classes in detail. I will start with a
discussion on file I/O.
File I/O
When performing file I/O, you have three options:
FileInputStream and FileOutputStream.
Use these classes when work-
ing with bytes.
FileReader and FileWriter.
Use these classes when working with
characters.
RandomAccessFile. Use this to both read and write to a file, allowing
you to access any location in the file.
The ChainDemo and ReadData classes discussed earlier in this chapter
demonstrated the FileInputStream and FileOutputStream classes. The con-
structors in FileInputStream, FileOutputStream, FileReader, and FileWriter are
similar, taking in a variation of the following parameters:
File file. A File object representing the file to be read from or written to.
String file. The string name of the file to be read from or written to.
boolean append. Used in the FileOutputStream and FileWriter construc-
tors, a value of true specifies that the data written to the file should be
appended to the end of the file. By default, writing to these streams does
not append, but instead overwrites the data in the file.
To demonstrate using these classes, the following CreateFileDemo program
creates a text file using the FileWriter class as the low-level writer. Study the
CreateFileDemo program, which creates a new file named scores.html, and try
to determine what the file will look like. Figure 16.5 shows the generated file.
Figure 16.5
HTML file generated from the CreateFileDemo program.
Search WWH ::




Custom Search