Can't save files on External Storage, even wit

2019-05-09 00:13发布

I'm developing an app for images manipulation on Android, but I'm stuck in writing the code for image saving.

Here's the method I use:

private void saveImageToExternalStorage(Bitmap finalBitmap) {
    String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-" + n + ".jpg";
    File file = new File(myDir, fname);
    if (file.exists())
        file.delete();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }


    // Tell the media scanner about the new file so that it is
    // immediately available to the user.
    MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });

}

Every time I execute this, FileOutputStream gives a FileNotFoundException.

My manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gabrielerestuccia.testimmagini">

<application
    ...
</application>

<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

</manifest>

I'm developing this on Android Studio 1.5.1 on Linux, using the built-in virtual Nexus 5 with Android 6.0.

Thanks for the help.

2条回答
姐就是有狂的资本
2楼-- · 2019-05-09 00:24
 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        _bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

        //you can create a new file name "test.jpg" in sdcard folder.
        File f = new File(Environment.getExternalStorageDirectory()
                                + File.separator + "test.jpg")
        f.createNewFile();
        //write the bytes in file
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());

        // remember close de FileOutput
        fo.close();
查看更多
爷的心禁止访问
3楼-- · 2019-05-09 00:46

I had the same problem on Android 6. This is because of new permission model.

You can check dynamically if you have permission with following piece of code:

private static boolean canWriteToExternalStorage(Context context) {
    return ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}

You can also enable writing permission for your app by going to Settings -> Apps -> Your App -> App Permissions and switch on Storage item.

In order to ask your user for this permission you should add in your Activity this piece of code:

public void onCreate(Bundle savedInstanceState) {
    ...
    checkWritingPermission();
}

@Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == REQUEST_CODE_PERMISSION) {
      if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // permission was granted
      } else {
        // permission wasn't granted
      }
    }
  }

  private void checkWritingPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
      if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
        // permission wasn't granted
      } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
      }
    }
  }
查看更多
登录 后发表回答