Text and Binary Files
Random-access files
Connect
How to connect to a random-access file
- You can use the classes in the OutputStream and InputStream hierarchies to read and write files sequentially. These are called sequential-access files.
- When you work with a sequential-access file, you read from the beginning of the file to the end, and you can add data only at the end of the file.
- You can use the RandomAccessFile class to read and write files randomly. These are called random-access files.
- When you work with a random-access file, you can move a pointer to any point in the file. Then, you can read and write data starting at that point.
- The metadata for a file includes information about the file such as its size, the date it was last modified, and so on.
Constructors of the RandomAccessFile class
Constructor | Throws |
---|---|
RandomAccessFile(File, stringMode) | FileNotFoundException |
RandomAccessFile(StringFileName, stringMode) | FileNotFoundException |
Access mode values
Value | Description |
---|---|
r | Open for reading only. |
rw | Open for reading and writing. If the file doesn't already exist, an attempt will be made to create it. |
rws | Open for reading and writing and also require that every update to the file data or the metadata for the file be written synchronously to the underlying storage device. |
rwd | Open for reading and writing and also require that every update to the file data be written synchronously to the underlying storage device. |
Note
- If you use one of the synchronized read-write modes, only one user at a time can update the file.
A File object that refers to a binary file
File file = new File("products.dat");
How to create a read-write RandomAccessFile object
RandomAccessFile productsFile = new RandomAccessFile(file, "rw");
How to create a read-only RandomAccessFile object
RandomAccessFile productsFile = new RandomAccessFile(file, "r");
How to create a synchronized read-write object
RandomAccessFile productsFile = new RandomAccessFile(file, "rws");