Sahand
Sahand

Reputation: 8360

Which mode for RandomAccessFile() overwrites existing file?

I want to write to a file called myFile.txt each time I open my program. If a file with that name from a previous run of the program exists, I want it to be overwritten. How do I accomplish this? I've read about:

RandomAccessFile f = new RandomAccessFile("myFile.txt", "rw");

but does this overwrite existing files? The documentation doesn't tell me if it does. Note that it's important that the old file be deleted in its entirety, I don't want the end of it to still be there if I only overwrite half of its length in the current run.

EDIT: Through testing I found out that "rw" doesn't delete existing file, it only overwrites for the top of the file and leaves the rest of it.

I found an alternative solution to fit my needs:

    RandomAccessFile file = new RandomAccessFile("myFile.txt", "rw");
    file.setLength(0);
    file.write(contentBytes);

But it would be nice if it was possible to do it in a shorter way.

Upvotes: 4

Views: 3621

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

RandomAccessFile does not have an opening mode that removes the file on opening. You can truncate it right after opening by calling setLength(0), the way your suggested. You can also get FileChannel and call truncate(0) on it.

If you use RandomAccessFile only to write contentBytes array, you can simplify your code by using FileOutputStream, which truncates the file on opening (unless you explicitly request file appending):

FileOutputStream fos = new FileOutputStream(f);
fos.write(contentBytes);

The reason I use RandomAccessFile is that is allows me to get the position of the file pointer, which I need in my application.

You should be able to get the position from FileOuputStream like this:

long pos = fos.getChannel().position();

Upvotes: 7

Related Questions