Languages
[Edit]
EN

Java - how to use RandomAccessFile class?

6 points
Created by:
JustMike
3488

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.