Java Reference
In-Depth Information
Table 8-7 displays the typical code for the declaration, construction, and
movement of data between the storage device and the program.
Table 8-7
Code to Create External Data Files
PROCESS
INPUT
OUTPUT
Declaration
DataInputStream input
DataOutputStream output
Construction
input = new
output = new
DataInputStream(new
DataOutputStream(new
FileInputStream(existingFilename));
FileOutputStream(newFilename));
Moving data
read() methods
write() methods
The stream of data is declared as either DataInputStream or
DataOutputStream; however, it is at the time of construction that the program
actually accesses the storage device. The file is opened if it is a read process; the file
is created if it is a write process. The DataOutputStream() method lets a program
write primitive Java data types to an output stream in a portable way. A program
then can use a DataInputStream() method to read the data from the data file.
The DataOutputStream and DataInputStream classes are wrapper classes,
which can be chained or connected to the corresponding File stream classes to
implement the reading or writing of formatted data. Wrapper classes were used
in earlier chapters to wrap the InputStreamReader to accept the keyboard buffer.
BufferedReader dataIn = new BufferedReader(new
InputStreamReader(System.in));
In the same way, you can wrap the FileInputStream inside the DataInputStream
for formatted data.
DataOutputStream output = new DataOutputStream(new
FileOutputStream(filename));
FileInputStream and FileOutputStream are used, respectively, to read and write
data to a given file. The file name is specified in the argument of the FileInput-
Stream() or FileOutputStream() method.
As indicated earlier, the BillPayer program creates a sequential file. If all
fields are complete, each time a user clicks the Submit button, formatted output
is sent to the data file. As with the BufferedReader, when Java attempts input or
output, the program must provide a way to catch possible errors. The try and
catch structure will be used to catch possible errors.
 
Search WWH ::




Custom Search