Writing and reading data in file using RandomAccessFile in java with examples

Updated:06/feb/2022 by Computer Hope

Here we are creating object of RandomAccessFile for writing data in file we are using writeInt(); method and for printing we use readInt();
Refer below code for more understanding

import java.io.*;
import java.util.*;
class FileExample8
{
	public static void main(String args[]) 
{
    try
    {
    	RandomAccessFile rac=new RandomAccessFile("d:/assignments/primenos.dat","rw");
    	Scanner kb=new Scanner(System.in);
    	System.out.println("Enter a no");
    	int n=kb.nextInt();
    	first:
    	for(int i=2;i<=n;i++)
    	{
    		for(int j=2;j<=i-1;j++)
    		{
    			if(i%j==0)
    				continue first;
    		}
    		rac.writeInt(i);
    	}
    	
    	System.out.println("Enter a pos");
    	int pos=kb.nextInt();
    	int count=(int)(rac.length()/4);
    	if(pos>count)
    		System.out.println("Wrong position");
    	else
    	{
    		rac.seek((pos-1)*4);
    		int primeno=rac.readInt();
    		System.out.println("Prime no at pos "+pos +" is "+primeno);
    		
    	}
    rac.close();	
    }
    catch(Exception ex)
    {
    	System.out.println("Error in writing or reading Object");
    }
}
}