Java Reference
In-Depth Information
READ-ANOTHER-RECORD
READ INPUT-FILE
AT END GO TO CLOSE-FILES
END-READ.
MOVE INPUT-RECORD TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
GO TO READ-ANOTHER-RECORD.
CLOSE-FILES.
CLOSE INPUT-FILE.
CLOSE OUTPUT-FILE.
To perform similar processing with Java, use the following code:
// Create streams related to a disk file.
FileInputStream instrm = new FileInputStream("in.dat");
FileOutputStream outstrm = new FileOutputStream("out.dat");
// Allocate a byte array to hold each record.
byte [] inRecord = new byte[100];
// Read the first record.
int bytesRead = instrm.read(inRecord);
// Loop until end of file when bytesRead = -1.
while (bytesRead != -1) {
// Write the record and read the next record.
outstrm.write(inRecord);
bytesRead = instrm.read(inRecord);
}
// Close the streams and files.
instrm.close();
outstrm.close();
Several problems could occur in processing the file. Errors could obviously occur
on opening either the input or the output file. Another, subtler type of problem is the
write() method chosen. The write() method will always write the 100-byte array. As
long as the input file contains 100-byte records and the file length is an exact multi-
ple of 100, the program would work fine. If that is not the case, the final read() could
read less than 100 bytes and the final write() could write extra bytes at the end of the
file. To prevent this problem, the write could be changed as follows:
// Write only the bytes read.
outstrm.write(inRecord, 0, bytesRead);
Search WWH ::




Custom Search