java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg(权限被拒绝)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47688354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:44:56  来源:igfitidea点击:

java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg (Permission denied)

javaandroid

提问by Midhun Pottammal

i am trying to download and store image using Async task in android , when clicking download button getting following error.

我试图在 android 中使用异步任务下载和存储图像,当单击下载按钮时出现以下错误。

    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/downloadedfilem.jpg (Permission denied)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.open(Native Method)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at java.io.FileOutputStream.<init>(FileOutputStream.java:108)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:113)
12-07 11:01:00.120 28478-28540/myoracle.com.quotes W/System.err:     at myoracle.com.quotes.WallpaperDeatilsActivity$ImageDownload.doInBackground(WallpaperDeatilsActivity.java:91)

WallpaperActivity.java

壁纸活动.java

class ImageDownload extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        int count;
        try {

            String root = Environment.getExternalStorageDirectory().toString();

            System.out.println("Downloading");
            URL url = new URL(params[0]);

            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();

            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);

            // Output stream to write file
            System.out.println(root);
            OutputStream output = new FileOutputStream(root+"/downloadedfilem.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // writing data to file
                output.write(data, 0, count);
                System.out.println(count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
           input.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
  1. Android Target Api 7.1.1
  1. Android 目标 API 7.1.1

Permissions added in manifest

清单中添加的权限

  1. android.permission.READ_EXTERNAL_STORAGE

  2. android.permission.WRITE_EXTERNAL_STORAGE

  1. android.permission.READ_EXTERNAL_STORAGE

  2. android.permission.WRITE_EXTERNAL_STORAGE

回答by Dharmishtha

You need to add runtime permission for OS Marshmallow or above. Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.

您需要为 OS Marshmallow 或更高版本添加运行时权限。添加此代码以获得允许在 onCreate 或图像下载过程之前的启动活动中运行时操作的权限。

if (!checkPermission()) {
    openActivity();
} else {
    if (checkPermission()) {
        requestPermissionAndContinue();
    } else {
        openActivity();
    }
}

Add this method outside onCreate

在外面添加这个方法 onCreate

private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {

        return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                ;
    }

private void requestPermissionAndContinue() {
    if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
                && ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
            AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
            alertBuilder.setCancelable(true);
            alertBuilder.setTitle(getString(R.string.permission_necessary));
            alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
            alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
                            , READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
                }
            });
            AlertDialog alert = alertBuilder.create();
            alert.show();
            Log.e("", "permission denied, show dialog");
        } else {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
                    READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    } else {
        openActivity();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    if (requestCode == PERMISSION_REQUEST_CODE) {
        if (permissions.length > 0 && grantResults.length > 0) {

            boolean flag = true;
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flag = false;
                }
            }
            if (flag) {
                openActivity();
            } else {
                finish();
            }

        } else {
            finish();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

private void openActivity() {
  //add your further process after giving permission or to download images from remote server.
}

回答by Rakesh

After Android 6.0 Marshmellow you need Runtime Permissions to access user private data like Local storage. https://developer.android.com/training/permissions/requesting.html

在 Android 6.0 Marshmellow 之后,您需要运行时权限才能访问本地存储等用户私有数据。https://developer.android.com/training/permissions/requesting.html