Languages
[Edit]
EN

Java - how to use RandomAccessFile class?

6 points
Created by:
Tehya-Blanchard
444

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

Alternative titles

  1. Java - basic random access file operations
  2. Java - how to make read and write operations for binary random access files?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join