Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append to a RandomAccessFile? Every time I run this code, the data get overwritten

Tags:

java

How do I append data with this snippet of code? Data is always being overwritten each time I run the code.

    try{
        RandomAccessFile fileWriter = new RandomAccessFile("Officers.txt", "rw");

        fileWriter.writeUTF(officerObject.getOfficerBadgeNum());
        fileWriter.writeUTF(officerObject.getOfficerFirstName());
        fileWriter.writeUTF(officerObject.getOfficerLastName());
        fileWriter.writeUTF(officerObject.getOfficerPrecint());

        fileWriter.close();
        System.out.println("Data Successfully Saved");
    }
    catch (IOException e) {
        System.out.println("Error in File. Could not SAVE Officer");
        e.printStackTrace();
    }
like image 222
Bond_James_Bond Avatar asked Mar 09 '23 14:03

Bond_James_Bond


1 Answers

Before you write, seek to the end of the file; first call length. I'd also prefer a try-with-resources. Like,

try (RandomAccessFile fileWriter = new RandomAccessFile("Officers.txt", "rw")) {
    fileWriter.seek(fileWriter.length());
    fileWriter.writeUTF(officerObject.getOfficerBadgeNum());
    fileWriter.writeUTF(officerObject.getOfficerFirstName());
    fileWriter.writeUTF(officerObject.getOfficerLastName());
    fileWriter.writeUTF(officerObject.getOfficerPrecint());
    System.out.println("Data Successfully Saved");
} catch (IOException e) {
    System.out.println("Error writing File. Could not SAVE Officer");
    e.printStackTrace();
}
like image 154
Elliott Frisch Avatar answered Apr 27 '23 03:04

Elliott Frisch