我正在尝试备份目录,但是我无法创建新文件夹。
首先,我将权限授予Manifest并已请求运行时权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
注意:我设备上的Environment.getExternalStorageDirectory()
返回内部存储而不是SdCard。但是,我使用文件选择器从SdCard中选择文件并正确地读取。
但是,这是我备份目录的方法:
private void backupSmaliDir(String smaliDir){
StringBuilder result = new StringBuilder("");
String backupDirPath = smaliDir+"-BACKUP";
StringBuffer listFile = getAllFiles(new File(smaliDir));
String[] lines = listFile.toString().split("\n");
result.append(String.format("BACKUP DIR: %s\nHAVE %s file to backup\n", backupDirPath, String.valueOf(lines.length)));
try {
for (String path : lines) {
File f = new File(path.replaceFirst(smaliDir, backupDirPath));
File newf = f.getParentFile();
result.append(String.format("\n Old: %s\n New: %s\n", path, newf.getCanonicalPath()+"/"+ new File(path).getName()));
boolean isCopied = false;
result.append(String.format("[w] EXISTS: %s | MKDIRS: %s\n", newf.exists(), newf.mkdirs()));
if (newf.exists() || newf.mkdirs()) {
// just copy path (FILE) to newf (FILE)
File fi = new File(path);
File fo = new File(newf.getCanonicalPath()+"/"+fi.getName());
copyFileUsingStream(fi, fo);
isCopied = true;
}
if (isCopied) result.append("\tCopied!\n");
else result.append("\tCanceled!\n");
}
} catch (IOException e) {
e.printStackTrace();
}
saveBackupLog(result.toString());
}
我不知道为什么newf.exists() || newf.mkdirs()
总是返回 False ,这意味着SdCard上没有新的目录。
有一些结果记录:
Smali Directory: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali
BACKUP DIR: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali-BACKUP
HAVE 141 file to backup
Old: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali/android/support/v9/app/a.smali
New: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali-BACKUP/android/support/v9/app/a.smali
[w] EXISTS: false | MKDIRS: false
Canceled!
Old: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali/android/support/v9/app/aa.smali
New: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali-BACKUP/android/support/v9/app/aa.smali
[w] EXISTS: false | MKDIRS: false
Canceled!
Old: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali/android/support/v9/app/ab.smali
New: /storage/AF7E-4CF0/toolbox/IPHONE_CONTROL_PSYCHO/smali-BACKUP/android/support/v9/app/ab.smali
[w] EXISTS: false | MKDIRS: false
Canceled!
.....
注意2:如果我将目录备份到{strong> 内部存储 中,例如/storage/emulated/0/tool
,则此代码可以正常工作!
那怎么了,我该怎么解决?
答案 0 :(得分:0)
在清单中添加以下内容:
<application
android:requestLegacyExternalStorage="true"
...
要求Manifest.permission.WRITE_EXTERNAL_STORAGE
不足以支持Android 10 +。