This is an example of using RandomAccessFile
class to read and write data to a file. Using RandomAccessFile
enable us to read or write to a specific location in the file at the file pointer. Imagine the file as a large array of data that have their own index.
In the code below you’ll see how to create an instance of RandomAccessFile
and define its operation mode (read / write). After we create an object we write some data, some book’s titles to the file. The last few line of the codes demonstrate how to read file data.
package org.kodejava.example.io;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
public static void main(String[] args) {
try {
// Let's write some book's title to the end of the file
String books[] = new String[5];
books[0] = "Professional JSP";
books[1] = "The Java Application Programming Interface";
books[2] = "Java Security";
books[3] = "Java Security Handbook";
books[4] = "Hacking Exposed J2EE & Java";
// Create a new instance of RandomAccessFile class. We'll do a "r"
// read and "w" write operation to the file. If you want to do a write
// operation you must also allow read operation to the RandomAccessFile
// instance.
RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");
for (String book : books) {
raf.writeUTF(book);
}
// Write another data at the end of the file.
raf.seek(raf.length());
raf.writeUTF("Servlet & JSP Programming");
// Move the file pointer to the beginning of the file
raf.seek(0);
// While the file pointer is less than the file length, read the
// next strings of data file from the current position of the
// file pointer.
while (raf.getFilePointer() < raf.length()) {
System.out.println(raf.readUTF());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The result of our program are:
Professional JSP The Java Application Programming Interface Java Security Java Security Handbook Hacking Exposed J2EE & Java Servlet & JSP Programming
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I clear the current command line in terminal? - February 14, 2019
- How do I generate random alphanumeric strings? - February 7, 2019
- Why do I get ArrayIndexOutOfBoundsException in Java? - January 29, 2019