Appending data to existing file : RandomAccessFile « File « Java Tutorial






import java.io.File;
import java.io.RandomAccessFile;

public class Main {
  public static void append(String fileName, String text) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);
    raf.writeBytes(text);
    raf.close();
  }

  public static void append(String fileName, byte[] bytes) throws Exception {
    File f = new File(fileName);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, "rw");
    raf.seek(fileLength);
    raf.write(bytes);
    raf.close();
  }
  public static void main(String[] args) throws Exception {
    append("c:\\tmp.txt", "Appended Data");
    append("c:\\tmp.bin", "Appended Data".getBytes());
  }
}








11.40.RandomAccessFile
11.40.1.RandomAccessFile Introduction
11.40.2.Employs RandomAccessFile to store ints and changes the value of the third int.
11.40.3.Seek in RandomAccessFile
11.40.4.Getting FileChannel from RandomAccessFile
11.40.5.Write int to RandomAccessFile using FileChannel
11.40.6.Use RandomAccessFile to save and read
11.40.7.Use RandomAccessFile to reverse a file
11.40.8.Test file pointer manipulation between FileChannel and RandomAccessFile objects.
11.40.9.Appending data to existing file