Clear file before writing new content into it (Java, Android)

Viewed 555

I'm using the following code to create a new file (binary or JSON) or rewrite an existing one in Android:

ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(uri, "w");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(bytes);
fileOutputStream.close();
pfd.close();

The problem is when the file already exists and its content size is larger, the old content remains. E.g. JSON can look like

[
    "a",
    "b"
]   "c",
    "d"
]

How do I clean the file before writing into it, or clear the remaining content?

3 Answers

Try using "wt" instead of w, to truncate the file (t) before writing to it.

you should change the initialization of FileOutputStream with a second parameter which say to overwrite the file content:

FileOutputStream(pfd.getFileDescriptor(), false); second parameter if its true then it append while its false it will overwrite.

ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(uri, "wt");
FileOutputStream fileOutputStream = new FileOutputStream(pfd.getFileDescriptor());
fileOutputStream.write(bytes);
fileOutputStream.close();
pfd.close();

Access mode for the file:

 1. "r" for read-only access,
 2. "w" for write-only access (erasing whatever data is currently in the file),
 3. "wa" for write-only access to append to any existing data, 
 4. "rw" for read and write access on any existing data, 
 5."rwt" for read and write access that truncates any existing file.

Try rwt it may do the job

Related