Question:
How can I append to a file in Java?The file is ASCII. It exists. The program hasrights to the file. I just need to add to the endof the file.
Answer:
You need to use Java’s RandomAccessFile class to accomplish this.Once you open a file with read and write permissions, you cansimply seek to the end position of the file and write your datafrom that point using one of the various write methods availablein that class:
For example, the following program appends a string from the command lineto the end of a file:public void write(byte b[]); public void write(byte b[], int off, int len); public void write(int b); public final void writeBoolean(boolean v); public final void writeByte(int v); public final void writeBytes(String s); public final void writeChar(int v); public final void writeChars(String s); public final void writeDouble(double v); public final void writeFloat(float v); public final void writeInt(int v); public final void writeLong(long v); public final void writeShort(int v); public final void writeUTF(String str);
——————- FileAppend.java —————–import java.io.*;public class FileAppend { // // Defining a main() routine allows the program to be // run as a standalone java application // public static void main(String argv[]) { if (argv.length != 2) { System.out.println(“Usage: FileAppend string outfile”); System.exit(1); } RandomAccessFile output = null; try { // Open the file for reading and writing output = new RandomAccessFile(argv[1], “rw”); } catch (Exception e) { System.out.println(“Couldn’t open ” + argv[1]); System.exit(1); } try { // seek to the end of the file output.seek(output.length()); // perform the write operation output.writeChars(argv[0] + ”
” ); } catch (Exception e) { System.out.println(“Error appending to file”); System.exit(1); } }}