
Write a program to write the details of an employee to a file. Details such as year of joining, department code, employee name and salary should be included. You must use RandomAccessFile to accomplish this. Now, read the data that has been written in the previous step and display it on the console. Using the seek pointer, retrieve the employee name and display it.

The given code accept the details from the user like year of joining, department code, employee name and salary. This data is then stored into the text file using RandomAccessFile class which is then displayed on the console.
import java.io.*;
class RandomAccessFileExample
{
public static void main(String[] args)
{
try{
File f=new File("c:/employee.txt");
RandomAccessFile randomFile=new RandomAccessFile(f,"rw");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter year of joining: ");
int year=Integer.parseInt(br.readLine());
System.out.print("Enter department code: ");
String dcode=br.readLine();
System.out.print("Employee Name: ");
String name=br.readLine();
System.out.print("Salary: ");
long sal=Long.parseLong(br.readLine());
randomFile.seek(f.length());
randomFile.writeBytes(Integer.toString(year)+" "+dcode+" "+name+" "+Long.toString(sal));
randomFile.close();
RandomAccessFile access = new RandomAccessFile(f, "r");
access.seek(0);
int len=(int)access.length();
for(int i = 0; i < len; i++){
byte b = access.readByte();
System.out.print((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.