我得到了

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();
}

当前回答

我也有同样的问题,但没有一个建议有用。但我发现了一个有趣的原因,那就是在实体设备Galaxy Tab上。

当USB存储打开时,外部存储的读写权限没有任何影响。 只要关闭USB存储,并使用正确的权限,你就会有问题解决。

其他回答

在我的例子中,我使用的是一个文件选择器库,它返回到外部存储的路径,但它从/root/开始。即使在运行时授予WRITE_EXTERNAL_STORAGE权限,我仍然得到错误EACCES(权限被拒绝)。 因此,使用Environment.getExternalStorageDirectory()来获取外部存储的正确路径。

例子: 无法写入:/root/storage/emulated/0/newfile.txt 可以写:/storage/emulated/0/newfile.txt

boolean externalStorageWritable = isExternalStorageWritable();
File file = new File(filePath);
boolean canWrite = file.canWrite();
boolean isFile = file.isFile();
long usableSpace = file.getUsableSpace();

Log.d(TAG, "externalStorageWritable: " + externalStorageWritable);
Log.d(TAG, "filePath: " + filePath);
Log.d(TAG, "canWrite: " + canWrite);
Log.d(TAG, "isFile: " + isFile);
Log.d(TAG, "usableSpace: " + usableSpace);

/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}

输出1:

externalStorageWritable: true
filePath: /root/storage/emulated/0/newfile.txt
isFile: false
usableSpace: 0

输出2:

externalStorageWritable: true
filePath: /storage/emulated/0/newfile.txt
isFile: true
usableSpace: 1331007488

我有同样的问题(API >= 23)。

解决方案https://stackoverflow.com/a/13569364/1729501对我有用,但断开应用程序进行调试是不实际的。

我的解决方案是在Windows上安装合适的adb设备驱动程序。谷歌USB驱动程序不适用于我的设备。

步骤1:下载适合您的设备品牌的adb驱动程序。

步骤2:进入设备管理器->其他设备->查找带有“adb”字样的条目->选择更新驱动程序->在步骤1中给出位置

我希望下面的所有内容/数据都属于“内部存储”。但是,您应该能够写入/sdcard。

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

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

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

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