Use RandomAccessFile class : RandomAccessFile « File Input Output « Java






Use RandomAccessFile class

  

import java.io.RandomAccessFile;

public class Main {

  public static void main(String[] args) throws Exception {
    RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");

    String books[] = new String[5];
    books[0] = "A";
    books[1] = "B";
    books[2] = "C";
    books[3] = "D";
    books[4] = "E";

    for (int i = 0; i < books.length; i++) {
      raf.writeUTF(books[i]);
    }
    raf.seek(raf.length());
    raf.writeUTF("Servlet & JSP Programming");

    raf.seek(0);

    while (raf.getFilePointer() < raf.length()) {
      System.out.println(raf.readUTF());
    }
  }
}

   
    
  








Related examples in the same category

1.Random IO
2.Using the RandomAccessFile class
3.The RandomAccessFile Class
4.Use RandomAccessFile to reverse a file
5.Using a Random Access File
6.A RandomAccessFile object that is tied to a file called employee.dat.
7.Reading UTF-8 Encoded Data
8.Appending data to existing file
9.The class demonstrates the use of java.io.RandomAccessFile
10.Readonly RandomAccessFile
11.Translate Charset
12.Use RandomAccessFile to save an object
13.Reverse a file with RandomAccessFile
14.Read from back
15.Using RandomAccessFile to read file saved DataOutputStreamUsing RandomAccessFile to read file saved DataOutputStream