FileOutputStream(FileDescriptor)覆盖而不是追加数据?

时间:2016-04-15 14:19:34

标签: java android

我通过FileOutputStream写入文件,该文件是通过构造函数打开FileDescriptor打开的。

我想要的行为:当我写文件时,我希望它是唯一的内容。例如。写“Hello”应该导致文件只包含“Hello”。

实际行为:每次我写一些东西时,都会被简单地加以说明。例如。在上面的例子中,我将得到“HelloHello”。

如何打开像我这样的FileOutputStream,让它不处于追加模式?

注意:我被迫使用FileDescriptor。

4 个答案:

答案 0 :(得分: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();
    }

答案 1 :(得分:0)

FileOutputStream(File file, boolean append)

使参数附加为false,因此每次调用时它都会覆盖现有数据。

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

答案 2 :(得分: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();
    }

答案 3 :(得分:0)

根据ContentProvider.java文件文档,可以在截断文件时使用“ rwt”模式读写文件。

ParcelFileDescriptor pfd = context.getContentResolver.openFileDescriptor(uri, "rwt");
FileOutputStream fos = new FileOutputStream(pfd.getFileDescriptor());
  

@param模式文件的访问模式。对于只读访问权限可能是“ r”,        “ rw”用于读写访问,或“ rwt”用于读写访问        会截断所有现有文件。

尽管这个问题是很久以前发布的,但还是希望得到帮助。

相关问题