4

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
zoltish
  • 2,122
  • 19
  • 37
  • http://stackoverflow.com/a/20398873/115145 – CommonsWare Apr 15 '16 at 14:23
  • Thanks @CommonsWare, I found that post prior as well but decided to post my question in hopes of another way that simply overwrites rather than truncates and then writes. Im working with big files. – zoltish Apr 15 '16 at 14:29
  • I would think that "simply overwrites" is the same as "truncates and then writes". – CommonsWare Apr 15 '16 at 14:32
  • It is unclear. For one, what should happen if the content to be written is larger than the current content in the file? – fge Apr 15 '16 at 14:43
  • Can you show a small sample code that shows how you create the FileDescriptor, open and write to the file? – pczeus Apr 15 '16 at 14:52

4 Answers4

2

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.

Liam
  • 469
  • 1
  • 6
  • 16
0

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();
    }
The Roy
  • 2,178
  • 1
  • 17
  • 33
0
FileOutputStream(File file, boolean append)

Make the argument append to false, so it overrides the existing data everytime when you call.

https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)

Hari Krishna
  • 3,658
  • 1
  • 36
  • 57
0

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();
    }
António Paulo
  • 351
  • 3
  • 18