首页 > 解决方案 > AndroidStudio - 如何使用 uri 将 SharedPreferences 文件从实习生复制到外部存储?

问题描述

我喜欢将我的 SharedPreferences 文件复制(备份和恢复)到外部存储

普通副本不起作用,我认为是因为自 Android 10 oder 11 以来的新限制

在清单中我设置了权限:

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

代码与

copyFile(in, out);

在内部工作,但外部路径不起作用

我的例子是复制同意

private void copyAsset(String filename){


    String dirPath = getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)+"/MyFiles";
   //String dirPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)+"/TasmoRemote";

    File dir = new File(dirPath);
    if(!dir.exists()){
        dir.mkdirs();
    }
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    try {
        in = assetManager.open(filename);
        File outFile = new File(dirPath, filename);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        Toast.makeText(this, dirPath + "Saved!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(this, "Failed!", Toast.LENGTH_SHORT).show();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
    }
}

使用 URI 创建文件也可以,但我不知道如何组合它,我可以将 ShardePreferences 文件复制到外部存储。

有谁知道解决我的问题的方法?

谢谢你

标签: android-studiofile-copying

解决方案


推荐阅读