This java code example illustrates how you can use the RandomAccessFile class.
The example in itself might seem pretty useless but the purpose is to show that you can both write to and read from a file with the same RandomAccessFile instance.
The RandomAccessFile class also enables you to get the current position of the file pointer by calling the method 'getFilePointer', or setting the file pointer position by calling the 'seek' method.
The behaviour of the RandomAccessFile class is similar to an array in the filesystem, but unlike an array you can alter the length of the file by calling the 'setLength' method.
If you are calling seek and then start to write data in an area that already contains data, it will be overwritten.
In this example we write two lines of code to the file, then we set the file pointer to the position at the end of the first line and read data from there and print it out.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* @author
*/
public class Main {
/**
* Example method for using the RandomAccessFile class
*/
public void testRandomAccessFile(String filename) {
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().testRandomAccessFile("myFile.txt");
}
}
The output to the file is:
First line
Second line
and the output to the console:
Second line
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment