当前位置: 首页 > 知识库问答 >
问题:

java.io.FileNotFoundException打开设备上的eacces失败(权限被拒绝)

淳于俊迈
2023-03-14

以下代码包括从服务器下载文件并将其保存在存储中,当设备有内部存储时,该代码可以正常工作。
但当我尝试使用没有内部存储的设备时,只使用外部存储时,我得到以下异常。

public void downloadFile(String dlUrl, String dlName) {
    int count;

    HttpURLConnection con = null;
    InputStream is = null;
    FileOutputStream fos = null;

    try {
        URL url = new URL( dlUrl );
        con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.connect();

        is = url.openStream();
        String dir = Environment.getExternalStorageDirectory() + Util.DL_DIRECTORY;
        File file = new File( dir );
        if( !file.exists() ){
            file.mkdir();
        }

        Util.LOG_W(TAG, "Downloading: " + dlName + " ...");

        fos = new FileOutputStream(file + "/" +  dlName);
        byte data[] = new byte[1024];

        while( (count = is.read(data)) != -1 ){
            fos.write(data, 0, count);
        }

        Util.LOG_D(TAG, dlName + " Download Complete!");


    } catch (Exception e) {
        Util.LOG_E(TAG, "DOWNLOAD ERROR = " + e.toString() );
        bServiceDownloading = false;
    }
    finally{
        try {
            if( is != null)
                is.close();
            if( fos != null)
                fos.close();
            if( con != null)
                con.disconnect();
        } catch (Exception e) {
            Util.LOG_E(TAG, "CLOSE ERROR = " + e.toString() );
        }
    }
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

有什么建议吗?原因是什么?顺便提一下,Environment.getExternalStorageDirectory()返回/mnt/sdcard/,file.mkdir()返回false。

共有1个答案

鄢翰藻
2023-03-14

在针对Android10或更高版本的应用程序上,该属性默认为“false”。

...

 类似资料: