android-studio - 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 文件复制到外部存储。
有谁知道解决我的问题的方法?
谢谢你
解决方案
推荐阅读
- maven - 在 Maven Web 应用程序 Worklight 8.0 中配置 mfp 服务器
- mysql - 不正确的字符串值:列的“\xC3”
- node.js - 节点获取请求显示空数组
- android - 更新 Sqlite 数据库后从自定义适配器对话框正按钮更新/刷新 Listview
- ruby-on-rails - 如何在带有 AJAX 的 ruby on rails 中使用cropperJS 上传图像?
- reactjs - React Modal中的反向选项卡不起作用
- beautifulsoup - Beautifulsoup:是否可以通过其值获取标签名称和属性名称?
- reactjs - 反应不发送到正确的 URL
- java - @Valid 注解不会停止空白字段
- python - 如何为pycharm安装pyaudio,当出现错误时(说因为没有安装轮子)