Java Reference
In-Depth Information
really a
PrintStream
(more about
PrintStream
s later). The
System
class also has a
method
setOut(PrintStream out
). You could direct all of the output going to the
console to a file simply by creating a new
PrintStream
from a
FileOutputStream
and
setting the
System.out
to use the new
PrintStream
. In other words,
System.out
is simply a
PrintStream
that, by default, goes to the console. When you code
System.out.println()
, however, the line will be output to wherever the
PrintStream
is directed, whether it be a console, a file, or even another program that might be
written to capture console output.
Stream-based I/O has the disadvantage that it has no concept of a record apart
from the code that is processing the data.
Let's assume for the moment that you wish to process the same
Account
file
with Java that you processed in the preceding example with COBOL. You have
taken the file from wherever it existed and brought it to the local machine with the
name account.dat. For simplicity, let's assume that the data is stored as ASCII and
no carriage return or line feeds have been added to the file. The file still consists of
the fixed 35-byte records. To process this file with Java, you would use the follow-
ing code:
// Create a stream related to a disk file.
FileInputStream instrm = new FileInputStream("account.dat");
// Allocate a byte array to hold each record.
byte [] accountRecord = new byte[35];
// Read the first record.
int bytesRead = instrm.read(accountRecord);
// Loop until end of file when bytesRead = -1.
while (bytesRead != -1) {
// Process each record and read the next record.
String accountNumber = new String(accountRecord, 0, 10);
String accountName = new String(accountRecord, 10, 25);
bytesRead = instrm.read(accountRecord);
}
// Close the stream and file.
instrm.close();
You opened the stream implicitly when you instantiated
FileInputStream
. Nei-
ther Java nor the operating system checked to make certain account.dat is a se-
quential file of fixed-length, with 35-byte records. If the file contained 34-byte
records, you would get no error. The
read()
method would dutifully return 35
bytes of data from the file, and you would process the file incorrectly unless you in-
corporated additional error-checking logic into the program. Additionally, since