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.
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 .
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.