android fileoutputstream 权限,关于ioexception:Android Studio内部存储FileOutputStream FileNotFound...

在Android Studio中尝试使用FileOutputStream在内部存储写入文件时遇到问题,引发FileNotFoundException。通过创建File对象并调用createNewFile()解决了找不到文件的问题,但随后遇到了IOException。Alarm类需要实现Serializable接口以支持ObjectOutputStream。无需额外权限,因为文件存储在应用的内部存储中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我正在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值