Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners RANDOM ACCESS FILE CONCEPT

Have Programming Question? Ask it here!
 
 
 


SANTOSH AGRASINGH
RANDOM ACCESS FILE CONCEPT
1 Answer(s)      2 years and 2 months ago
Posted in : Java Beginners


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.


Advertisement
View Answers

June 15, 2012 at 3:42 PM


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){}
    }
}


Related Tutorials/Questions & Answers:
Advertisements
 

 

 

DMCA.com