Appending data to existing file : RandomAccessFile « File Input Output « Java






Appending data to existing file

  

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());
  }
}

   
    
  








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.Use RandomAccessFile class
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