
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 BufferedWriter class to write even number between 2 and 10 into text file.Then using the RandomAccessFile, we have wrote numbers from 1 to 5. 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");
BufferedWriter bw=new BufferedWriter(new FileWriter(f,true));
for(int i=2;i<=10;i++){
if(i%2==0){
bw.write(Integer.toString(i));
bw.newLine();
}
}
bw.close();
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();
System.out.println("Length: " + i);
access.seek(i-3);
for(int ct = 0; ct < i; ct++){
byte b = access.readByte();
System.out.println((char)b);
}
}
catch(Exception e){}
}
}