在android4.0的手机上直接创建某个文件的路径一直报这个错:android.system.ErrnoException: open failed: ENOENT (No such file or directory)
我的代码如下:
try { long timestamp = System.currentTimeMillis(); String time = formatter.format(new Date()); String fileName = "crash-" + time + "-" + timestamp + ".txt"; String file_dir = getFilePath(); // if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { File dir = new File(file_dir); if (!dir.exists()) { dir.mkdirs(); } File file = new File(file_dir + fileName); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); fos.write(sb.toString().getBytes()); //发送给开发人员 sendCrashLog2PM(file_dir + fileName); fos.close(); // } return fileName; } catch (Exception e) { Log.e(TAG, "an error occured while writing file...", e); }
而且,我也在Androidmainfest.xml里配置了读写的权限,可还是不行。
于是,我在网上查了很多资料,最终解决了,解决方案如下:
在API23+以上,不止要在AndroidMainfet.xml里面添加权限
1 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />2 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
还要在代码里添加请求的权限:
// Storage Permissions 2 private static final int REQUEST_EXTERNAL_STORAGE = 1; 3 private static String[] PERMISSIONS_STORAGE = { 4 Manifest.permission.READ_EXTERNAL_STORAGE, 5 Manifest.permission.WRITE_EXTERNAL_STORAGE }; 6 7 /** 8 * Checks if the app has permission to write to device storage 9 * 10 * If the app does not has permission then the user will be prompted to11 * grant permissions12 * 13 * @param activity14 */15 public static void verifyStoragePermissions(Activity activity) {16 // Check if we have write permission17 int permission = ActivityCompat.checkSelfPermission(activity,18 Manifest.permission.WRITE_EXTERNAL_STORAGE);19 20 if (permission != PackageManager.PERMISSION_GRANTED) {21 // We don't have permission so prompt the user22 ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,23 REQUEST_EXTERNAL_STORAGE);24 }25 }
在调用保存的方法前点用即可。