英文:
empty file after recording and turning off the mobile device after 1-2 seconds
问题
我将文件写入目录后,等待1-2秒,然后从设备中取出电池。写入后,我打开文件并将其输出到日志中,以确保它已记录。因此它已成功记录。但在打开设备后,我打开文件,而它是空的。
可能的原因是什么?
以前用过FileOutputStream/FileInputStream、FileWriter/FileReader以及来自Apache Commons IO的FileUtils进行读写操作。
public static void storeForReversal(XmlTag sourceTag_TrnAddRq) {
String toStore = sourceTag_TrnAddRq.buildXmlString();
File sdFile = new File(getFilesDir(), "reversal");
try {
FileUtils.writeStringToFile(sdFile, toStore, "US-ASCII");
} catch (IOException e) {
ZLog.add(MyApplication.TAG, "ERROR store file Reversal: ", e);
}
}
public static String restoreForReversal() {
String result = "";
File sdFile = new File(getFilesDir(), "reversal");
try {
result = FileUtils.readFileToString(sdFile, "US-ASCII");
} catch (IOException e) {
ZLog.add(MyApplication.TAG, "ERROR restore file Reversal: ", e);
}
return result;
}
英文:
I write the file to the directory and after 1-2 seconds I remove the battery from the device. After writing, I open the file and output it to the log in order to make sure that it is recorded. So it is recorded successfully. But after turning on the device I open the file and it is empty.
What could be the reason?
Used to read and write FileOutputStream/FileInputStream, FileWriter/FileReader, FileUtils from Apache Commons IO.
public static void storeForReversal(XmlTag sourceTag_TrnAddRq) {
String toStore = sourceTag_TrnAddRq.buildXmlString();
File sdFile = new File(getFilesDir(), "reversal");
try {
FileUtils.writeStringToFile(sdFile, toStore, "US-ASCII");
} catch (IOException e) {
ZLog.add(MyApplication.TAG, "ERROR store file Reversal: ", e);
}
}
public static String restoreForReversal() {
String result = "";
File sdFile = new File(getFilesDir(), "reversal");
try {
result = FileUtils.readFileToString(sdFile, "US-ASCII");
} catch (IOException e) {
ZLog.add(MyApplication.TAG, "ERROR restore file Reversal: ", e);
}
return result;
}
[Device File Explorer][1]
[1]: https://i.stack.imgur.com/HHwiH.jpg
答案1
得分: 0
为了确保在紧急断电时将信息保存在文件中,您需要使用 fo.getFD().sync()
:
try (FileOutputStream fo = new FileOutputStream(sdFile)) {
fo.write(text.getBytes());
fo.flush();
fo.getFD().sync();
} catch (IOException e) {
Log.e(TAG, "");
}
英文:
To ensure that information is saved in a file during an emergency power off, you need to use fo.getFD().sync()
:
try (FileOutputStream fo = new FileOutputStream(sdFile)) {
fo.write(text.getBytes());
fo.flush();
fo.getFD().sync();
} catch (IOException e) {
Log.e(TAG, "");
}
专注分享java语言的经验与见解,让所有开发者获益!
评论