The first type of data file that we have looked at is a text file or ASCII file. An ASCII file gets its name from the fact that all information is stored in ASCII code, or simple text that is human readable. ReadMe files that come with hardware and software are examples of files that are often stored as text or ACSII files.
Binary files are those in which all information is stored in binary format, that is, in the same format that it is stored in computer memory. When an int is stored in a text file, it is changed to string format, for example, instead of the number 45 being stored in base two, each digit is stored as an ACSII code, 4 is stored as ASCII code 52 and 5 is stored as ASCII code 53. In a binary file, the number 45 would be stored as its base two value of the whole number.
Binary files are often stored in record format, that is sets of information that have a fixed length. . The following chart lists the space in bytes for each of the Java primitive data types. Strings do not have a fixed length, in a record, a maximum number of characters must be decided upon. For example a last name may have a limit of 25 letters. Each letter would take up two bytes of storage.
Given the following record and the fact that name can use a maximum of 20 characters, calculate the required binary storage for the following record:
private String name;
private long empNum;
private double hourlyRate;
private double hoursWorked;
private double regularPay;
private double overtimePay;
RandomAccessFile supports the notion of a file pointer. The file pointer indicates the current location in the file. When the file is first created, the file pointer is set to 0, indicating the beginning of the file. Calls to the read
and write
methods adjust the file pointer by the number of bytes read or written.
In addition to the normal file I/O methods that implicitly move the file pointer when the operation occurs, RandomAccessFile contains three methods for explicitly manipulating the file pointer.
int skipBytes(int)
--Moves the file pointer forward the specified number of bytesvoid seek(long)
--Positions the file pointer just before the specified bytelong getFilePointer()
--Returns the current byte location of the file pointer Example demo code: