Java.io.FileNotFoundException:在设备上打开失败EACCES(权限被拒绝)

25

当设备只有外部存储时,下面的代码从服务器下载文件并将其保存在存储中。但是,如果设备没有内部存储,则会发生以下异常:

java.io.filenotfoundexception open failed eacces (permission denied)

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
尝试使用 File file = new File( dir + "/" + dlName ); - Pankaj Kumar
很遗憾,结果是一样的。顺便说一下,file.mkdir()返回false,我认为这就是问题所在。@PankajKumar - Lazy Ninja
选择权在你手中...你可以在断开设备与电脑的连接后进行检查。 - Pankaj Kumar
你最终解决了吗? - hB0
1
@hB0 我没有用最理想的方式解决它,但我已经发布了一个解答,说明了我是如何处理这个问题的。希望能对你有所帮助。 - Lazy Ninja
显示剩余5条评论
11个回答

0

我曾经遇到过同样的问题。我在清单文件中正确地使用了写入和读取权限,但它仍然无法工作!解决方案非常愚蠢:在运行应用程序之前从电脑上拔掉手机。似乎当您的手机连接为“大容量存储器”时,应用程序无法访问外部存储。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接