by Dinesh Thakur Category: Stream

Java also allows you to access the contents of a file in random order i.e. data items can be read and written in any order. This is especially useful in direct access applications such as banking systems, airline reservation systems, Automatic Teller Machine (ATM) etc. where the desired information must be located immediately. Random access files (or direct access files) are analogous to arrays, where each element is accessed directly by means of its index number. Java provides class that enables you to perform random access file input and output operations as opposed to sequential file I/O offered by ByteStream and CharacterStream classes.

When a data file is opened for random read and write access, an internal file pointer is set at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data item. For example, when reading an in t value using readlnt() , 4 bytes are read from the file and the file pointer moves 4 bytes ahead from the previous file pointer position.

Similarly, when reading a double value using readDouble () , 8 byte are read from the file pointer and the file pointer moves 8 bytes ahead from the previous file pointer position.


class RandomFileExample
     public static void main(String[] args)
              RandomAccessFile file = new RandomAccessFile("std.dat","rw");    
              for(int i=0;i<50;i++)
                   System.out.println("Length of File After Writing Data is : "+file.length());
                   System.out.println("First Number is : "+file.readInt());
                   System.out.println("Second Number is : "+file.readInt());
                   System.out.println("Current Length of File is : "+file.length());
                   catch(Exception e)

RandomAccessFile in Java Examples

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles