Share on Google+Share on Google+

Java RandomAccessFile Example

Advertisement
Here you will learn about the RandomAccessFile class.

Java RandomAccessFile Example

Here you will learn about the RandomAccessFile class. In the given code, we have used BufferedWriter class to write even number between 2 and 10 into text file. Then using the RandomAccessFile, we have wrote numbers from 1 to 5. The seek() function displays the the last 3 digits of file.

Example:

import java.io.*;

class RandomAccessFileExample
{
public static void main(String[] args) 
{
try{
File f=new File("c:/num.txt");
BufferedWriter bw=new BufferedWriter(new FileWriter(f,true));
for(int i=2;i<=10;i++){
if(i%2==0){
bw.write(Integer.toString(i));
bw.newLine();
}
}
bw.close();
RandomAccessFile randomFile=new RandomAccessFile(f,"rw");
for(int i=1;i<=5;i++){
randomFile.seek(f.length());
randomFile.writeBytes(Integer.toString(i));
}
randomFile.close();
RandomAccessFile access = new RandomAccessFile(f, "r");
int i=(int)access.length();
System.out.println("Length: " + i);
access.seek(i-3); 
for(int ct = 0; ct < i; ct++){
byte b = access.readByte();
System.out.println((char)b); 
}
}
catch(Exception e){}
}
}

Output: Following data has been added to the text file 'num.txt'.

2
4
6
8
10
12345

Last three numbers from the file will get displayed on the console.

Length: 21
3
4
5

Advertisements

Advertisement

Posted on: December 12, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.