delete contents of a binary file before writing to it again

1k views Asked by At

I have a simple write method using RandomAccessFile to write an ArrayList of Strings in a *.bin file. Depending on user input, the size of the ArrayList is going to change after every user access. This is the only method that writes to this file.

@FXML protected void writeToFile(){

    try(RandomAccessFile file = new RandomAccessFile(fileName, "rw")){

        // file.setLength(0);
        file.seek(0);
        file.writeUTF(wordsArrayList.toString());
        file.close();

    }catch (IOException e){
        System.out.println("error writing from writeToFile()");
    }
}

How can I clear the contents of the file (not delete the file and create a new one) using RandomAccessFile before writing to it again in order to avoid *.bin files like below? Setting the length to zero doesn't seem to work.

*.bin file view

0

There are 0 answers