无法将文件从外部存储复制到Android 9中的数据目录

时间:2019-02-12 07:13:53

标签: android

我正在使用此方法将数据库文件从外部存储复制到我的应用程序的数据目录中。此方法在Android 8.0及更低版本上可以正常使用,但在Android 9上则不能。

    try {
        File sd = Environment.getExternalStorageDirectory();
        File data  = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String  currentDBPath= "//data//" + "com.mypackage"
                    + "//databases//" + "dictionary";
            String backupDBPath  = "/MyApp/dictionary";
            File backupDB = new File(data, currentDBPath);
            File currentDB  = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getBaseContext(), "Imported successfully",
                   Toast.LENGTH_LONG).show();

        }
    } catch (Exception e) {

    }

显示“已成功导入”吐司,但未复制文件。该应用程序不会崩溃,logcat上也不会显示任何内容。

1 个答案:

答案 0 :(得分:1)

自Android 7.0起,您需要使用FileProvider才能访问目录中的文件。
签出documentation并查看this example