Using a Random Access File in Java

In this section, you will learn the Random Access File features provided by java io package.


C:\nisha>java RandAccessFile
Enter File name : Filterfile.txt
Write Successfully

Download this example.

The another program reads the characters from a file using the readByte( ) method.


public class ReadAccessFile{
  public static void main(String[] argsthrows IOException{
  BufferedReader in = new BufferedReader(new InputStreamReader(;
  System.out.print("Enter File name : ");
  String str = in.readLine();
  File file = new File(str);
  System.out.println("File does not exist.");
  //Open the file for both reading and writing
  RandomAccessFile rand = new RandomAccessFile(file,"r")
  int i=(int)rand.length();
  System.out.println("Length: " + i);;  //Seek to start point of file
  for(int ct = 0; ct < i; ct++){
  byte b = rand.readByte(); //read byte from the file
  System.out.print((char)b)//convert byte into char
  catch(IOException e)

Output of the Program:

C:\nisha>java ReadAccessFile
Enter File name : Filterfile.txt
Length: 30
??t h i s i s a f i l e

Download this Program:



Share on Google+Share on Google+

Using a Random Access File in Java

Posted on: April 17, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Using a Random Access File in Java   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
July 27, 2012
Small error, confusing in-code comment

In the comment above the call to the RandomAccessFile constructor, it says that it opens the file for both reading and writing. That confused me because the call to the constructor only had "r" in the second argument instead of "rw". I just recently learned about random access files, so that's why i found it so confusing. Anyway, I just wanted to point it out so no one else who is fairly new to java gets confused.