我想在设备中创建目录和文件。
但是当File.mkdirs()总是返回false时... 我不知道为什么!
我甚至在清单中添加了这样的权限:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="pkg.pkg.pkg">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
....
这是我的代码:
File directory = null;
File file = null;
String dir = "";
String folderName = "test";
String sdcard = Environment.getExternalStorageState();
if(sdcard.equals(Environment.MEDIA_MOUNTED)){
dir = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
dir = Environment.getRootDirectory().getAbsolutePath();
}
directory = new File(dir, folderName);
if(!directory.exists()) {
directory.mkdirs(); // return false here.
}
if(directory.isDirectory()){
file = new File(directory.getAbsolutePath(), fileName);
if(file.exists()){
String tempFileName = et_export.getText().toString();
// Check duplicate file name
for(int i=1;;i++){
fileName = tempFileName + " (" + i + ").png";
file = new File(directory.getAbsolutePath(), fileName);
if(!file.exists()) break;
} // for
} // if(file.exists())
} // if(directory.isDirectory())
问题是什么......?
答案 0 :(得分:0)
https://developer.android.com/training/permissions/requesting.html
从Android 6.0(API级别23)开始,用户在应用程序运行时向应用程序授予权限,而不是在安装应用程序时。
您需要手动编写权限授予部分(除了在清单中定义它之外)。
以下是developer.android.com的片段
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
// MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}