编写RandomAccessFile时权限被拒绝

时间:2016-04-30 09:55:14

标签: java android

编辑:我的问题不是Android permission doesn't work even if I have declared it的重复,因为我已经在运行时请求了权限

Edit2:将文件写入Environment.getexternalstoragedirectory即可,但是sdcard会出现该错误

嘿我试图用RandomAccessFile写一个带有sdcard的mp3文件,这是我的代码:

public void save(String newFilename) throws IOException, NotSupportedException {
    if (file.compareTo(new File(newFilename)) == 0) {
        throw new IllegalArgumentException("Save filename same as source filename");
    }
    RandomAccessFile saveFile = new RandomAccessFile(newFilename, "rw");
    try {
        if (hasId3v2Tag()) {
            saveFile.write(id3v2Tag.toBytes());
        }
        saveMpegFrames(saveFile);
        if (hasCustomTag()) {
            saveFile.write(customTag);
        }
        if (hasId3v1Tag()) {
            saveFile.write(id3v1Tag.toBytes());
        }
    } finally {
        saveFile.close();
    }
}

private void saveMpegFrames(RandomAccessFile saveFile) throws IOException {
    int filePos = xingOffset;
    if (filePos < 0) filePos = startOffset;
    if (filePos < 0) return;
    if (endOffset < filePos) return;
    RandomAccessFile randomAccessFile = new RandomAccessFile(this.file.getPath(), "r");
    byte[] bytes = new byte[bufferLength];
    try {
        randomAccessFile.seek(filePos);
        while (true) {
            int bytesRead = randomAccessFile.read(bytes, 0, bufferLength);
            if (filePos + bytesRead <= endOffset) {
                saveFile.write(bytes, 0, bytesRead);
                filePos += bytesRead;
            } else {
                saveFile.write(bytes, 0, endOffset - filePos + 1);
                break;
            }
        }
    } finally {
        randomAccessFile.close();
    }
}

我在logcat

中收到此错误
java.io.FileNotFoundException: /storage/15D5-14F7/Musics/Music/Dream On.mp3: open failed: EACCES (Permission denied)

但我有写入和读取权限,为什么会发生这种情况?

2 个答案:

答案 0 :(得分:1)

java.io.FileNotFoundException: /storage/15D5-14F7/Musics/Music/Dream On.mp3: open failed: EACCES (Permission denied)

这似乎是removable storage上的一个位置。您没有对Android 4.4+设备上可移动存储上的任意位置的读取或写入权限。

  

但我有写入和读取权限

您可能拥有external storage的读取和/或写入权限。外部存储不是可移动存储。

答案 1 :(得分:0)

如果您写了此权限,则可以访问该权限。但是在棉花糖之上,您必须包括如何处理运行时权限。

这是解决方案链接。

https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/