Java RandomAccessFile open mode

Introduction

Mode Meaning
"r" a read-only mode. IOException for writing to the file.
"rw" a read-write mode. The file is created if it does not exist.
"rws"Same as "rw", file content and its metadata are saved immediately
"rwd"Same as "rw", file content is saved immediately

import java.io.RandomAccessFile;

public class Main {
  public static void main(String[] args) throws Exception {
    // Open the file in read-write mode
    RandomAccessFile raf = new RandomAccessFile("Main.java", "rw");

    int counter = raf.readInt();
    String msg = raf.readUTF();/*  ww  w .jav a 2s  .  c  o  m*/

    System.out.println("File Read Counter: " + counter);
    System.out.println("File Text: " + msg);

    raf.close();
  }
}



PreviousNext

Related