How do I use RandomAccessFile class?
Category: java.io, viewed: 2180 time(s).
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.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; public class RandomAccessFileExample { public static void main(String[] args) { try { // // 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 opeartion to the RandomAccessFile // instance. // RandomAccessFile raf = new RandomAccessFile("books.dat", "rw"); // // 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"; for (int i = 0; i < books.length; i++) { raf.writeUTF(books[i]); } // // 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 (FileNotFoundException e) { e.printStackTrace(); } 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
Related Examples
- How do I store properties as XML file?
- How do I load properties from XML file?
- How do I convert InputStream to String?
- How do I convert string into InputStream?
- How do I get an exception stack trace message?
- How do I use Console class to read user input?
- How do I store objects in file?
- How do I use DataInputStream and DataOutputStream?
- How do I create a directories recursively?
- How can I get current working directory?
|
|