Reputation: 2302
Im writing to a file through a FileOutputStream
that is opened via its constructor taking a FileDescriptor
.
My desired behavior: When I write to the file I want that to be the only content of it. E.g. writing "Hello" should result in the file containing just "Hello".
Actual behavior: Each time I write something, it is simply appeneded. E.g. in the above example I will get "HelloHello".
How can I open a FileOutputStream like Im doing, and have it not be in append mode?
Note: I am forced to use a FileDescriptor.
Upvotes: 5
Views: 4845
Reputation: 669
According to the ContentProvider.java file documentation, you can use "rwt" mode to read and write in file in truncating it.
ParcelFileDescriptor pfd = context.getContentResolver.openFileDescriptor(uri, "rwt");
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
@param mode Access mode for the file. May be "r" for read-only access, "rw" for read and write access, or "rwt" for read and write access that truncates any existing file.
Hope this help despite that the question was posted a long time ago.
Upvotes: 2
Reputation: 351
FileOutputStream outputStream;
try {
outputStream = openFileOutput("your_file", Context.MODE_PRIVATE);
//Context.MODE_PRIVATE -> override / MODE_APPEND -> append
outputStream.write("your content");
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 3548
FileOutputStream(File file, boolean append)
Make the argument append to false, so it overrides the existing data everytime when you call.
Upvotes: 0
Reputation: 2208
If you use FileOutoutStream then the ctor provides an option for you to specify whether you want to open the file to append or not. Set it to false and it will work.
OutputStream out = null;
try {
out = new FileOutputStream("OutFile", false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Upvotes: 0