读取外部存储设备时找不到文件异常 [英] File not found exception when reading external storage

查看:250
本文介绍了读取外部存储设备时找不到文件异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前的代码可以正常运行,即使现在它对于Android 6之前的设备也可以正常运行,但是在Nexus 5 6.0.1中,我无法从外部存储访问数据.

Earlier the code was working totally fine, and even now it works fine for pre Android 6 devices, but in my Nexus 5, 6.0.1, I am unable to access data from external storage.

它显示文件未找到异常

java.io.FileNotFoundException:/storage/emulated/0/Download/********/*****:打开失败:ENOENT(无此类文件或目录)

java.io.FileNotFoundException: /storage/emulated/0/Download/********/*****: open failed: ENOENT (No such file or directory)

为了将数据写入存储,我要求获得运行时存储权限,而这部分似乎还可以.

For writing the data to storage, I am asking for runtime storage permission and that part seems to be fine.

推荐答案

在您的主要活动onCreate()方法中进行此设置:

Make this in you onCreate() method of main activity:

if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
    // Do something for lollipop and above versions
    checkPermission();
    if (!checkPermission()) {
        requestPermission();
    }
}

这段代码在onCreate()之外:

private boolean checkPermission(){
    int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
    if (result == PackageManager.PERMISSION_GRANTED){
        return true;
    } else {
        return false;
    }
}

private void requestPermission(){
    ActivityCompat.requestPermissions(activity,new String[]{
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.CAMERA,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CALL_PHONE},PERMISSION_REQUEST_CODE
    );
}

此代码将检查版本是否高于Lollipop OS.如果是这样,那么它将在加载应用程序时征求用户的许可.

This code will check whether the version is above Lollipop OS. If so, then it will ask for permission to user while loading app.

希望它会对您有所帮助.经过测试.正常工作.

Hope it will help you. Tested. Working properly.

这篇关于读取外部存储设备时找不到文件异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆