Move file point when reading binary file with RandomAccessFile in Java

Description

The following code shows how to move file point when reading binary file with RandomAccessFile.

Example


 /*  w w  w.j  a va2  s. c o m*/

import java.io.IOException;
import java.io.RandomAccessFile;

public class Main {
  public static void main(String[] args) {
    try {
      RandomAccessFile raf = new RandomAccessFile("c:\\temp\\RAFsample.txt", "rw");
      raf.writeInt(10);
      raf.writeInt(43);
      raf.writeInt(88);
      raf.writeInt(455);

      // change the 3rd integer from 88 to 99
      raf.seek((3 - 1) * 4);
      raf.writeInt(99);
      raf.seek(0); // go to the first integer
      int i = raf.readInt();
      while (i != -1) {
        System.out.println(i);

        i = raf.readInt();
      }
      raf.close();
    } catch (IOException e) {
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip