-1

I'm trying to store an object to a data file, and I can create the file, but when I try append anything to the file it simply creates a new file and overwrites the old file.

My create code:

public void createObject(Object object)
{

    //File outFile = new File(Environment.getExternalStorageDirectory(), "foobar.data");
    try
    {

        File outFile = new File(Environment.getExternalStorageDirectory(), "foobar.data");
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(outFile));
        out.writeObject(object);
        out.close();
    }
    catch (IOException e)
    {
        Log.i("CreateObject", "Write - Catch error can't find .data");
    }
    finally
    {
        try
        {
            // out.close();
            Log.i("CreateObject", "Closed successfully!");
        }
        catch (Exception e)
        {
            Log.i("CreateObject", "Write - Failed to close object output stream.");
        }
    }

I tried using the code at https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html and replaced my try with

FileOutputStream fos = new FileOutputStream("foobar.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(event);
oos.close();

but my program goes straight to catch. The catch error is java.io.FileNotFoundException: /foobar.data: open failed: EROFS (Read-only file system)

Dan
  • 3
  • 2

1 Answers1

0

new FileOutputStream(...) has an append parameter. If you don't use it, or don't set it to true, you will get a new file.

However this won't work anyway. You can't append to object streams, at least not without taking special measures. All you will get when you read it is StreamCorruptedException: invalid type code AC at the join.

user207421
  • 305,947
  • 44
  • 307
  • 483