getFilesDir() 与 getDatabasePath()

getFilesDir() vs getDatabasePath()

我正在通过 SQLCipher 在我的 Android 混合 Cordova 应用程序中实现对 SQLite 数据库的访问,该应用程序使用一个自定义插件(即由我编写)。 SQLCipher 文档 - 以及其他在 Android 中使用 SQLite 的教程 - 继续参考 Context.getDatabasePath。在我的插件代码中,我存储了其他应用程序文件并广泛使用 Context.getFilesDirgetDatabasePathgetFilesDir 有何不同。例如,由于 OS 决定通过删除存储在 Context.getFilesDir 中的一些文件来创建 "some more room",它是否承诺数据库将持久存在并且不会以某种方式被转储的更好机会?

两者都解析到同一个目录。 getDatabasePath 呼叫 getDatabasesDir.

getDatabasesDir:

  private File getDatabasesDir() {
        synchronized (mSync) {
            if (mDatabasesDir == null) {
                if ("android".equals(getPackageName())) {
                    mDatabasesDir = new File("/data/system");
                } else {
                    mDatabasesDir = new File(getDataDir(), "databases");
                }
            }
            return ensurePrivateDirExists(mDatabasesDir);
        }
    }

getFilesDir:

  @Override
    public File getFilesDir() {
        synchronized (mSync) {
            if (mFilesDir == null) {
                mFilesDir = new File(getDataDir(), "files");
            }
            return ensurePrivateDirExists(mFilesDir);
        }
    }

请注意,返回的 File 在两种方法中都由 ensurePrivateDirExists 解析,其具有由 getDataDir 解析的相同输入目录。

getDataDir

Returns the absolute path to the directory on the filesystem where all private files belonging to this app are stored.

因此,您的情况没有区别

不要忘记返回的路径可以改变,正如doc所说:

The returned path may change over time if the calling app is moved to an adopted storage device, so only relative paths should be persisted.