从外部SD卡读取文件,导致fileNotFoundException打开失败:ENOENT android Marshmallow 6.0.1

时间:2016-09-01 10:39:08

标签: android filenotfoundexception

我正在尝试从android Marshmallow 6.0.1中的外部SD卡读取文件,并希望转换为字节,但它给出了fileNotFoundException。但我的相同代码适用于6.0及以下版本。我的代码如下:

private String convertFileToByteArray(File file) { //file path as: /storage/emulated/0/abc.doc
        byte[] byteArray = null;
        try {

            File f=new File(file.toString());
            Log.e("File EXISTs: >>",""+f.exists());

           //getting error in this line,giving fileNotFoundException
            FileInputStream inputStream = new FileInputStream(file); 
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024 * 11];
            int bytesRead = 0;

            while ((bytesRead = inputStream.read(b)) != -1) {
                bos.write(b, 0, bytesRead);
            }

            byteArray = bos.toByteArray();

            Log.e("Byte array", ">" + byteArray);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return Base64.encodeToString(byteArray, Base64.NO_WRAP);
    }

任何人都可以告诉我,我在这里做错了什么。 PS:我也给了运行时权限。

2 个答案:

答案 0 :(得分:1)

在marshmallow中,在try块中使用此代码进行外部存储。

public  boolean isexternalStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
    if (android.Manifest.permission.WRITE_EXTERNAL_STORAGE == PackageManager.PERMISSION_GRANTED) {
        Log.v(TAG,"Permission is granted");
        return true;
    } else {

        Log.v(TAG,"Permission is revoked");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        return false;
    }
}
else { //permission is automatically granted on sdk<23 upon installation
    Log.v(TAG,"Permission is granted");
    return true;
}

}

答案 1 :(得分:0)

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

使用权限

请浏览documentation