Current Page:
NeXtMidas Training
File Handlers
Lab 1
Part 3
|
|
- Part 3 - Reading and writing:
-
Now lets add methods so we can read/write data in the file. For this we are going to
follow what DataFile is doing and add three methods (you will see why in Lab 2).
- getDataBuffer(..)
- read(..)
-
The read(..) method is relatively short, but it can be a bit confusing
the first time. So we will just use the code below and then explain what is
happening line-by-line.
public int read (Data data, int elements) {
int bytes = elements * BPE; // 1
int bytesRead = read(data.getBuf(), 0, bytes); // 2
int numRead = bytesRead / BPE; // 3
// 4
if (Shell.rep != EEEI) { // 5
Convert.rep(data.getBuf(), 0, getFormat(), // 6
numRead, EEEI, Shell.rep); // 7
} // 8
return numRead; // 9
}
-
Line 1: Convert from number of elements to number of bytes.
-
Line 2: Read bytes from the file and insert them directly in
to the data buffer (data.getBuf() accesses the raw byte array).
The method being called was provided by BaseFile and reads
raw bytes from the file.
-
Line 3: Convert from number of bytes actually read to number of elements.
-
Lines 5-8: If the data we just read in (little-endian, EEEI)
does not match the data representation of the local host system, we need to
convert it to match. The
Convert.rep(..)
method will do that for us.
-
Line 9: Return the number of elements read in.
- write(..)
-
The write(..) method is similar to the read(..) method.
public int write (Data data, int elements) {
if (Shell.rep != EEEI) {
Convert.rep(data.getBuf(), 0, getFormat(), elements, Shell.rep, EEEI);
}
int bytes = elements * BPE;
int numWritten = write(data.getBuf(), 0, bytes);
return numWritten / BPE;
}
- continued on next page
|
|
|