Android: 无法附加到 ObjectOutputFile
Android: Can't append to ObjectOutputFile
我正在尝试将一个对象存储到一个数据文件中,并且我可以创建该文件,但是当我尝试将任何内容附加到该文件时,它只会创建一个新文件并覆盖旧文件。
我的创建代码:
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.");
}
}
我尝试使用 https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html 处的代码并将我的 try
替换为
FileOutputStream fos = new FileOutputStream("foobar.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(event);
oos.close();
但我的程序直接进入 catch
。捕获错误是 java.io.FileNotFoundException: /foobar.data: open failed: EROFS (Read-only file system)
new FileOutputStream(...)
有一个 append 参数。如果您不使用它,或者不将其设置为 true,您将获得一个新文件。
但是这无论如何都行不通。您不能附加到对象流,至少不能不采取特殊措施。当你阅读它时,你将得到的只是 StreamCorruptedException: invalid type code AC
在加入。
我正在尝试将一个对象存储到一个数据文件中,并且我可以创建该文件,但是当我尝试将任何内容附加到该文件时,它只会创建一个新文件并覆盖旧文件。
我的创建代码:
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.");
}
}
我尝试使用 https://docs.oracle.com/javase/8/docs/api/java/io/ObjectInputStream.html 处的代码并将我的 try
替换为
FileOutputStream fos = new FileOutputStream("foobar.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(event);
oos.close();
但我的程序直接进入 catch
。捕获错误是 java.io.FileNotFoundException: /foobar.data: open failed: EROFS (Read-only file system)
new FileOutputStream(...)
有一个 append 参数。如果您不使用它,或者不将其设置为 true,您将获得一个新文件。
但是这无论如何都行不通。您不能附加到对象流,至少不能不采取特殊措施。当你阅读它时,你将得到的只是 StreamCorruptedException: invalid type code AC
在加入。