Credits

Thursday, January 13, 2011

Java's RandomAccessFile Class

RandomAccessFile class of Java is used for reading from and writing into a physical file. Unlike File class where it is used to display only file information, RandomAcessFile class is used instead for a more dynamic use.

The key concept around this class is the fact that it uses file pointer to skip anywhere in the file. Thus, methods like seek() and skipBytes() are used around the file.

Find below a program that uses this class to write something into our file.

[+/-] show/hide


/*use of Random Access File */

import java.io.*;
public class RandAccessFile{
public static void main(String [] args) throws IOException{
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
System.out.print("Enter file name: ");
String str=in.readLine();

File file = new File (str);
if (!file.exists())
{
System.out.println("File does not exist.");
}
try{
//open aa file for both reading and writing
RandomAccessFile rand=new RandomAccessFile(file,"rw");
rand.seek(file.length(); //seek to end of file
rand.writeBytes("Data.txt,"); //write to end of file
rand.close();
System.out.println("Write successfully.);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}

AddThis