Java I/O How to - Store ints and change the value of the third int








Question

We would like to know how to store ints and change the value of the third int.

Answer

//from www.  j  a v a2  s. c o m

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

public class MainClass {
  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.