0

I have a method that's supposed to write an object to a file. I've tried a variety of methods but I either don't write to the file or I go into my catch statement, my code is as follows:

public void createFoo(Foo foo)
{
    ObjectOutputStream out = null;
    try
    {
        out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\PERSON\\AndroidStudioProjects\\PROJECT\\bar.dat"));
        out.writeObject(event);
        Log.i("CreateFoo", "Write success");
    }
    catch (IOException e)
    {
        Log.i("CreateFoo", "Write - Catch error can't find .dat");
    }
    finally
    {
        try
        {
            out.close();
        }
        catch (Exception e)
        {
            Log.i("CreateFoo", "Write - Failed to close object output stream.");
        }
    }
}

I've tried looking at other threads but I'm still having trouble, my Foo object also has implements Serializable in its declaration.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Dan
  • 3
  • 2

2 Answers2

0

Your Android device does not have a C:\\Users\\PERSON\\AndroidStudioProjects\\PROJECT\\ directory, largely because Android is not Windows, so Android does not have drive letters. Also, you cannot write to just any directory in Android -- your app is limited to internal storage, external storage, and (on Android 4.4+) removable storage.

Also, in the future, when you ask questions on Stack Overflow about how your app is crashing, use LogCat and post the stack trace.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I'm using the Android Studio emulator so I thought it would look in its file directory for the .dat. Will storing to external storage store in a Windows directory? – Dan Mar 13 '15 at 00:52
  • @Dan External storage for the emulator is a disk image. Files your app on the emulator writes to external storage will be inside that disk image file. – CommonsWare Mar 13 '15 at 01:02
0

Replacing

out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\PERSON\\AndroidStudioProjects\\PROJECT\\bar.dat"));

with

File outFile = new File(Environment.getExternalStorageDirectory(), "bar.data");
        out = new ObjectOutputStream(new FileOutputStream(outFile));

Did the trick, thanks for the help!

Dan
  • 3
  • 2