我得到了

open failed: EACCES(权限被拒绝)

myOutput = new FileOutputStream(outFileName);

我检查了根目录,并尝试了android.permission.WRITE_EXTERNAL_STORAGE。

我该如何解决这个问题?

try {
    InputStream myInput;

    myInput = getAssets().open("XXX.db");

    // Path to the just created empty db
    String outFileName = "/data/data/XX/databases/"
            + "XXX.db";

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
    buffer = null;
    outFileName = null;
}
catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

当前回答

我曾经在模拟器中运行应用程序时观察到这种情况。在模拟器设置中,您需要正确指定外部存储(“SD卡”)的大小。默认情况下,“外部存储”字段为空,这可能意味着没有这样的设备,即使在清单中授予了权限,也会抛出EACCES。

其他回答

也许答案是这样的:

在API >= 23个设备上,如果你安装了app (app不是系统app),你应该在“设置-应用程序”中检查存储权限,每个应用程序都有权限列表,你应该检查它!试一试

2022 Kotlin请求许可的方式:

private val writeStoragePermissionResult =
   registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->}

private fun askForStoragePermission(): Boolean =
   if (hasPermissions(
           requireContext(),
           Manifest.permission.READ_EXTERNAL_STORAGE,
           Manifest.permission.WRITE_EXTERNAL_STORAGE
       )
   ) {
       true
   } else {
       writeStoragePermissionResult.launch(
           arrayOf(
               Manifest.permission.READ_EXTERNAL_STORAGE,
               Manifest.permission.WRITE_EXTERNAL_STORAGE,
           )
       )
       false
   }

fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
    ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}

我也有同样的问题……<uses-permission在错误的地方。这是正确的:

 <manifest>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        ...
        <application>
            ...
            <activity> 
                ...
            </activity>
        </application>
    </manifest> 

users -permission标记需要在application标记之外。

我在Galaxy S5 (android 6.0.1)上尝试在DCIM/camera文件夹中写入图像时遇到了同样的错误,我发现只有这个文件夹是受限制的。我可以简单地写入DCIM/任何文件夹,但不是在相机。 这应该是基于品牌的限制/定制。

当您的应用程序属于系统应用程序时,它不能访问SD卡。