Java IO – RandomAccessFiles

Introduction

A Random access file behaves like an array of bytes. It can be used to both read and write bytes. RandomAccessFile allows to read or write data at a particular position. It implements the DataInput and DataOutput interfaces and hence allows reading and writing java primitive types.

The file can be opened in both read only mode and read write mode. This examples opens the file in read write mode.

After writing the data into the RandomAccessFile, we will attempt to read it. First let us see what the current position of the file is:

The command below gives the number of bytes that have been written so far and the position of the pointer. The current position should be equal to the length of the file.

Set the pointer at the beginning of the file so that we can start reading it.

The int is stored in 4 bytes, so the pointer is now at 4. We could read the next two byte or read till the end of the file and store all byes read into a string. If the file was large, we would have used a buffer

There are ways to convert the byte array to a char array, but lets do it the hard way. Char is stored as two bytes in java, so we expect the length of the byte array to be a multiple of 2 (note that for this example, we know for sure that except for the first four bytes, all other bytes are part of the string ‘stringA’, that is the reason we will attempt to convert all the remaining bytes to char.)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.