EN
Java - how to use RandomAccessFile class?
6
points
In Java it is possible to read and write random access files in following way.
1. RandomAccessFile
class example
package com.dirask.examples;
import java.io.IOException;
import java.io.RandomAccessFile;
public class Program {
public static void main( String[] args ) throws IOException {
RandomAccessFile file = new RandomAccessFile( "data.dat", "rw" );
try {
file.seek( 0 );
file.writeByte( 10 ); // 1B - offset 0
file.writeShort( 11 ); // 2B - offset 1
file.writeInt( 12 ); // 4B - offset 3
file.writeUTF( "Text" ); // offset 7
file.seek( 3 );
int number = file.readInt();
System.out.println( "Number: " + number );
} finally {
file.close();
}
}
}
Output:
Number: 12