如果在写入文件时发生错误,如何防止擦拭文件?

问题描述 投票:1回答:1

这是我在许多应用程序中遇到的问题。我想更改文件中的信息,该文件具有过时的版本。在这种情况下,在将歌曲添加到播放列表后,我将更新记录播放列表的文件。 (供参考,我正在为Android创建一个应用程序。)

问题是我是否运行此代码:

FileOutputStream output = new FileOutputStream(file);
output.write(data.getBytes());
output.close();

并且如果在尝试写入文件时发生IOException,则数据将丢失(因为创建FileOutputStream的实例会清空文件)。是否有更好的方法来执行此操作,因此,如果发生IOException,则旧数据保持不变?还是仅当文件为只读时才会发生此错误,所以我只需要检查一下?

我唯一的“解决方法”是将错误通知用户,并向该用户提供正确的数据,用户必须手动更新该数据。虽然这可能对开发人员有效,但是如果发生这种情况,可能会发生很多问题。另外,在这种情况下,用户没有权限自己编辑文件,因此“解决方法”根本不起作用。

很抱歉是否有人问过这个问题。搜索时找不到结果。

提前感谢!

java android file fileoutputstream
1个回答
1
投票
重命名可能会失败。为确保安全,可以根据文件创建的时间来命名文件。例如,如果您的文件名为save.dat,则可以将文件保存的时间(从System.currentTimeMillis())添加到文件名的末尾。然后,无论以后发生什么(包括删除旧文件或重命名新文件失败),您都可以恢复最近一次成功的保存。我在下面提供了一个示例实现,该实现将时间表示为附加到文件扩展名的16位零填充十六进制数字。名为save.dat的文件将另存为save.dat00000171ed431353或类似名称。

// name includes the file extension (i.e. "save.dat"). static File fileToSave(File directory, String name) { return new File(directory, name + String.format("%016x", System.currentTimeMillis())); } // return the entire array if you need older versions for which deletion failed. This could be useful for attempting to purge any unnecessary older versions for instance. static File fileToLoad(File directory, String name) { File[] files = directory.listFiles((dir, n) -> n.startsWith(name)); Arrays.sort(files, Comparator.comparingLong((File file) -> Long.parseLong(file.getName().substring(name.length()), 16)).reversed()); return files[0]; }

© www.soinside.com 2019 - 2024. All rights reserved.