->The following program demonstrates
the use of FileReader class.
import
java.io.*;
class
FileRead
{
public static void main(String args[]) throws
Exception
{
FileReader fr = new
FileReader(“file2.txt”);
int i = fr.read(); // read first character
while(i != -1) // not end-of-file
{
char ch = (char)i; //convert into
character
data = data + ch; // append to string
data
i = fr.read();
}
System.out.println(“The contents of
file2.txt are : “ + data);
fr.close();
} //
end of main
} // end of class
NOTE:
The problem of using the above stream classes to create files is that
FileOutputStream class stores data as an array of bytes while FileWriter class
stores data as an array of characters.
->
But, in most real-time applications files are used to store data as a set of
records. That is, assume an Employee data file. This file needs to store emp_id
as integer, name as string, basic as float etc., But, the above classes are not
used to represent data in the form of their corresponding data types. To
overcome this problem, we can use RandomAccessFile which represents data as its
equalent Primitive data types.
->The following program
demonstrates the use of RandomAccessFile class
/* Program to implement Random Access
Files */
import
java.io.*;
class
RandomReadWrite
{
int empno;
String name;
float basic;
RandomAccessFile raf;
BufferedReader br;
RandomReadWrite() // constructor
{
try{
raf = new RandomAccessFile(“emp.dat”,”rw”);
// rw—read & write mode
br = new BufferedReader(new
InputStreamReader(System.in));
}
catch(Exception e){System.out.println(e);}
public
void readEmpData()
{
try{
System.out.println(“Enter Employee
Number “);
empno =
Integer.parseInt(br.readLine());
System.out.println(“Enter Employee
Name “);
name = br.readLine();
System.out.println(“Enter Employee
Salary “);
basic =
Float.parseFloat(br.readLine());
}
catch(Exception e){System.out.println(e);}
}
// end of readEmpData()
public
void writeEmpFile()
{
int size = raf.length(); // find the size of
file
raf.seek(size); // move cursor to end of
file
String ch = “yes”;
while(ch.equals(“yes”))
{
readEmpData();
raf.writeInt(empno) ;
raf.writeUTF(name);
raf.writeFloat(basic);
System.out.println(“Any more
records(yes/no) “);
ch = br.readLine();
} // end while
} // end of WriteEmpFile()
public void readEmpFile()
{
raf.seek(0); // place cursor at the start of
file
int size = raf.length();
while(raf.getFilePointer()<size)
{
int id = raf.readInt();
String na = raf.readUTF();
float sal = raf.readFloat();
System.out.println(id + “ “ + na + “
“ + sal);
} // end while
raf.close();
} // end of ReadEmpFile()
public static void main(String args[])
{
RandomReadWrite r = new RandomReadWrite();
r.writeEmpFile();
r.readEmpFile();
} // end of main
}
// end of class