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