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 */

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 (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("Data.txt,"); //write to end of file
System.out.println("Write successfully.);
catch (IOException e)

No comments: