Friday, January 15, 2010

Java's Random Access File

Processing of records is faster once there is an instant search for any of the record. Java provides Random Access File that extends from the Object class and inherits DataInput and DataOutput interface.

Do check the program below that allow an added input or entry to an existing file.

[+/-] show/hide

/*use of Random Access File */

/* program must add to end of data.txt the new text*/
public class RandAccessFile{
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader (new InputStreamReader (;
System.out.print("Enter file name: ");
String str=in.readLine();

File file = new File ("\\Documents and Settings\\Rose\\My Documents\\NetBeansProjects\\SampleExercises\\src\\",str);
if (!file.exists())
System.out.println("File does not exist.");
//open aa file for both reading and writing
RandomAccessFile rand=new RandomAccessFile(file,"rw");; //seek to end of file
rand.writeBytes("This is my new text."); //write to end of file
System.out.println("Write successfully.");
catch (IOException e)

No comments: