Languages
[Edit]
EN

Java - how to use RandomAccessFile class?

6 points
Created by:
JustMike
26120

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
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join