
Write a program to use a File object and print even numbers from two to ten. Then using RandomAccessFile write numbers from 1 to 5. Then using seek () print only the last 3 digits

In the given code, we have used RandomAccessFile to write number from 1 to 5 in the text file. The seek ()function displays the the last 3 digits of file.
import java.io.*;
class RandomAccessFileExample
{
public static void main(String[] args)
{
try{
File f=new File("c:/num.txt");
RandomAccessFile randomFile=new RandomAccessFile(f,"rw");
for(int i=1;i<=5;i++){
randomFile.seek(f.length());
randomFile.writeBytes(Integer.toString(i));
}
randomFile.close();
RandomAccessFile access = new RandomAccessFile(f, "r");
int i=(int)access.length();
access.seek(i-3);
for(int ct = 0; ct < i; ct++){
byte b = access.readByte();
System.out.println((char)b);
}
}
catch(Exception e){}
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.