我在获取权限以从手机上的原始文件保存文件时遇到问题。我明确地表明了这一点:

<uses-permission android:name="android.permissions.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permissions.READ_EXTERNAL_STORAGE" />


在我使用onclick的Java中,我具有保存文件的功能

saveTestButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

                InputStream in = null;
                FileOutputStream fout = null;
                try {
                    in = getResources().openRawResource(R.raw.testsound);
                    String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
                    String filename = "testsound.mp3";
                    fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));

                    final byte data[] = new byte[1024];
                    int count;
                    while ((count = in.read(data, 0, 1024)) != -1) {
                        fout.write(data, 0, count);
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
        }

    });


并检查权限:

private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}


当我尝试通过单击应用程序中的按钮保存此文件时,出现错误:


  W / System.err:java.io.FileNotFoundException:/storage/emulated/0/Downloadtestsound.mp3:打开失败:EACCES(权限被拒绝)


怎么了?

最佳答案

我相信这是您的问题:

fout = new FileOutputStream(new File(downloadsDirectoryPath + filename));


请改用以下内容:

fout = new FileOutputStream(new File(downloadsDirectoryPath , filename));


您仅具有/storage/emulated/0/Download/testsound.mp3的权限,而没有/storage/emulated/0/Downloadtestsound.mp3的权限

10-07 13:03