我正在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。 我还没有找到解决此问题的方法。 有人可以给我一些提示,告诉我为什么会出现此异常。 是否可能需要添加一些我不知道的权限类型?
我认为创建FileOutputStream时应提供完整路径。
另请注意,您创建的文件位于应用程序的内部存储(context.getFilesDir())中,您不需要任何额外的权限。
请参阅此处的文档-https://developer.android.com/reference/java/io/ObjectOutputStream
Only objects that support the java.io.Serializable interface can be written to streams.
因此,您必须为Alarm类实现Serializable接口,并且其所有字段也必须可序列化才能使用ObjectOutputStream。
您可以从文档中找到更多信息。
其他参考
序列化Java:哪些类需要"实现序列化"?
https://stackoverflow.com/a/28789107/9640177