[英]Files are getting deleted from the SD card
我已经开发了一个服务,它将在我收到“ON_BOOTUP_COMPLETED”意图时启动,
在我的服务的“onCreate”中,我编写了在设备的 SD 卡中创建文本文件的逻辑。
以下是我曾经这样做的逻辑:
File abc = new File(Environment.getExternalStorageDirectory()+"\abc.txt");
if(!abc .exists())
abc.createNewFile();
abcwriter = new FileWriter(abc);
我在其他方法中使用“abcwriter”将一些内容写入文本文件。 到目前为止,它工作正常。
但是当重新启动设备时,我观察到“abc.txt”文件正在再次创建。
但我在创建文件“if(.abc.exists())”之前进行了检查。 但仍会创建新文件。
我怀疑当我重新启动设备时,我的文件被删除了。 这是 android 行为..?
如果是,请帮助我我能做些什么来确保我的文件不会再次创建。
如果要将 append 传递给文件,则必须使用下面的构造函数并将 true 作为第二个参数传递。 否则,每次运行代码时(重新启动时),它都会被覆盖。同时摆脱createNewFile()
调用,你不需要它,因为作者会创建它。
FileWriter(File file, boolean append)
abcwriter = new FileWriter(abc);
-> 这一行(重新)创建文件。
确保仅在需要时调用它:
File abc = new File(Environment.getExternalStorageDirectory()+"\abc.txt");
if(!abc.exists()) {
// abc.createNewFile(); -> this is not needed since following line handles this
abcwriter = new FileWriter(abc);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.