我正在研究android studio,我想在内部存储中编写/存储一个文件。我知道堆栈溢出有几个这样的问题。我已经设法从这些代码中获取此代码。
public static void writeObj(Alarm alarm, Context context){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream("ArrayList.txt", true);
oos = new ObjectOutputStream(fos);
oos.writeObject(alarm);
oos.flush();
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这段代码对我不起作用。我设法弄清楚我得到了一个FileNotFound异常,因为FileOutputStream无法创建我的文件。所以我做了一些挖掘并在我的try / catch上面添加了这个(在FileOpenOutputStream中用f替换“ArrayList.txt”)。
File f = new File(context.getFilesDir(),"ArrayList.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
这为我创建了文件,让我通过FileNotFound异常捕获,但现在我得到一个IOException。我一直无法找到解决这个问题的方法。有人可以给我一些提示,说明为什么我会得到这个例外。是否可能需要添加到我不知道的Manifest文件中的某种类型的权限?
请参阅此处的文档 - https://developer.android.com/reference/java/io/ObjectOutputStream
只有支持java.io.Serializable接口的对象才能写入流。
因此,您必须为Alarm类实现Serializable接口,并且其所有字段也必须是Serializable才能使用ObjectOutputStream。
您可以从文档中找到更多信息。
其他参考
Serialization Java: which classes need to "implement Serializable"?