繁体   English   中英

将对象写入文件

[英]Writing object to file

我有一种应该将对象写入文件的方法。 我尝试了多种方法,但是要么不写文件,要么进入catch语句,我的代码如下:

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.");
        }
    }
}

我尝试查看其他线程,但仍然遇到麻烦,我的Foo对象在其声明中也implements Serializable

您的Android设备没有C:\\\\Users\\\\PERSON\\\\AndroidStudioProjects\\\\PROJECT\\\\目录,主要是因为Android不是Windows,因此Android没有驱动器号。 此外,您不能仅写入Android中的任何目录-您的应用仅限于内部存储外部存储和(在Android 4.4+上) 可移动存储

另外,将来,当您在Stack Overflow上询问有关应用程序崩溃的问题时,请使用LogCat并发布堆栈跟踪

更换

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

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

搞定了,谢谢您的帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM