【问题标题】:Android - File empty after crashAndroid - 崩溃后文件为空
【发布时间】:2014-09-30 11:03:03
【问题描述】:

我正在开发我的游戏,它将用户数据保存在设备上的某些文件中。游戏崩溃后,用户不会检索这些数据。崩溃后,相应的文件立即为空。此外,在下方创建了一个备份文件来保存新数据,以确保不删除旧数据。这个备份文件也是空的。

我不明白他们怎么可能是空的。 您可以在保存功能下方找到:

算法形式:

copy file to file_backup
if save data to file_temp then
    move file_temp to file
else 
    delete file_temp

C++ 形式:

const std::string path = "dataPlayer.dat";
const std::string backupPath = atPath + "_back";

if (PlatformInterface::fileExists(path))
{
    if (PlatformInterface::fileExists(backupPath))
       PlatformInterface::removeFile(backupPath);
    PlatformInterface::copyFile(path, backupPath);
}

const std::string tempPath = path + "_temp";
// Save in compact form.
XMLError error = dataDocument.SaveFile(tempPath.c_str(), true);
if (error != XML_NO_ERROR)
{
     PlatformInterface::removeFile(tempPath);
}
else
{
    bool moved = PlatformInterface::moveFile(tempPath, path);
    if (!moved)
    {
        PlatformInterface::removeFile(tempPath);
    }
}

如果你有任何想法,我会感谢你!

编辑: PlatformInterface::copyFile(path, backupPath) 方法:

public static void copyFile(final String path, final String destination) {
    try {
        if (!new File(path).exists())
            return;
        InputStream in = new FileInputStream(path);
        OutputStream out = new FileOutputStream(destination);
        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

文件似乎已正确关闭。

【问题讨论】:

  • 重要的是:它为什么会崩溃以及如何防止这种情况..
  • 崩溃可能是由于应用程序错误,但也可能是由于设备关机(电池电量低,设备严重故障)。

标签: android c++ android-ndk


【解决方案1】:

由于程序异常终止,缓冲区可能不会刷新到文件中。

为了防止这种情况发生,请在每次写入后刷新文件(关闭流或关闭文件描述符)并使用 append 重新打开它。

根据经验,ext 文件系统(如 Android 中的文件系统)比 NTFS 更多地使用磁盘缓存(它刷新较晚而不是较早)。

【讨论】:

  • 我将 copyFile 函数发布到我的问题中。似乎文件在写入后正确关闭。你觉得这样可以吗?
  • 这看起来像 Java 代码,您是否使用 JNI 进行文件传输?您正在 Java 中正确关闭流 - 仍然不能保证在 hdd 上刷新。尝试使用 stdio(fprintf 和 fscanf)实现复制文件。关于您的应用程序的一些问题:您确定 java 接收到的路径是正确的吗?你有任何例外吗?您的应用程序在复制文件期间是否崩溃?您要复制的文件是空的吗?
  • 是的,我正在使用 JNI。 (写作)
  • 是的,我正在使用 JNI。我不确定java是否正确接收了路径。也不例外(取出电池会导致崩溃)。文件不为空(通过 USB 检查)。我正在尝试使用 FileChannel::force(true)、File::flush() 和 FileDescriptor::sync() 方法。
  • 好吧,如果您在复制过程中崩溃了您的应用程序,那么无论您如何关闭流(这是您想要实现的目标吗?),什么都没有是正常的。检查 java 路径(一个简单的 println 就可以了),只是为了确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多