在mainFest中有
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
对于较新的操作系统,它会检查权限
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
如果它没有返回true,它将请求许可
ActivityCompat.requestPermissions(activity, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 5);
只有拥有权限时才会尝试创建文件
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String sysDownloadPath = directory.getPath();
try {
if (!directory.exists() && !directory.mkdirs()) {
//shouldn't happen in here
/* Checks if external storage is available for read and write */
String state = Environment.getExternalStorageState();
String externalStorageAvailable = (Environment.MEDIA_MOUNTED.equals(state)) ?
"ext-ST available" :
"ext-ST NOT available"; }
} catch (Exception e) { //<=== did not caught exception here
}
String fileName = ‘SD_20170404.pdf’;
String newFilePath = (sysDownloadPath + "/" + fileName);
File newFile = new File(newFilePath);
try {
newFile.createNewFile();// <=== throws at this one
} catch (Exception e) {
fatal Exception: java.lang.Exception: open failed: EACCES (Permission denied), newFile.getPath():/storage/emulated/0/Download/SD_20170404.pdf
OS 5,6和7会发生(并非总是如此)任何建议?谢谢!