我使用了 Adeel Turk 的许可建议。我不需要检查构建版本,因为我只使用 Android 6 (API 23)。
//
// Get storage write permission
//
public boolean isStoragePermissionGranted(int requestCode) {
if (ContextCompat.checkSelfPermission(MyActivity.this,android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
//Now you have permission
return true;
} else {
ActivityCompat.requestPermissions(MyActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestCode);
return false;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Now you have permission
// Check file copy generated the request
// and resume file copy
if(requestCode == WFileRequest)
try {
copyFile(OriginalDataFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
虽然这通过了权限例外,但它没有回答如何在默认应用程序目录之外创建文件夹的问题。以下代码获得许可并在 /storage/emulated/0 处创建一个名为 AppData 的文件夹,该文件夹显示在设备存储的顶层。在 Adeel Turk 的示例中,权限请求代码 WFileRequest 设置为 4,但我知道您可以使用任何数字。权限请求回调然后检查请求代码并使用最初写入的文件的名称再次调用 copyFile 例程。
大部分代码都使用了论坛中how to create a folder in android External Storage Directory? 和How to copy programmatically a file to another directory? 的其他帖子中的示例
public void copyFile(String SourceFileName) throws FileNotFoundException, IOException
{
String filepath = "";
//
// Check permission has been granted
//
if (isStoragePermissionGranted(WFileRequest)) {
//
// Make the AppData folder if it's not already there
//
File Directory = new File(Environment.getExternalStorageDirectory() + "/AppData");
Directory.mkdirs();
Log.d(Constants.TAG, "Directory location: " + Directory.toString());
//
// Copy the file to the AppData folder
// File name remains the same as the source file name
//
File sourceLocation = new File(getExternalFilesDir(filepath),SourceFileName);
File targetLocation = new File(Environment.getExternalStorageDirectory() + "/AppData/" + SourceFileName);
Log.d(Constants.TAG, "Target location: " + targetLocation.toString());
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}