【问题标题】:Getting error when I try to download file当我尝试下载文件时出现错误
【发布时间】:2011-07-12 06:55:29
【问题描述】:

我在网上找到了这个源代码并稍作修改。但我收到一条错误消息:java.io.FileNotFoundException /data/datafile.zip。 我应该怎么做才能让它运行?我必须先创建文件吗?

谢谢,西格德

private Thread checkUpdate = new Thread() {
    public void run() {
        try {
            long startTime = System.currentTimeMillis();
            Log.d("Zip Download", "Start download");
            File file = new File(Environment.getDataDirectory(), "datafil.zip");
            Log.d("Zip Download", file.getAbsolutePath());

            URL updateURL = new URL("http://dummy.no/bilder/bilder/XML_Item_Expo_01.zip");
            URLConnection conn = updateURL.openConnection();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);

            int current = 0;
            while((current = bis.read()) != -1){
                baf.append((byte)current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();
            Log.d("Zip Download", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
        } catch (Exception e) {
            Log.d("Zip Download", "Error: " + e);
        }
    }
};

【问题讨论】:

    标签: android file download


    【解决方案1】:

    似乎是权限错误。你可能写错地方了。在下面的链接中检查答案,

    Data directory has no read/write permission in Android

    【讨论】:

      【解决方案2】:

      Environment.getDataDirectory() 不返回可以放置文件的路径。您应该改用以下方法之一:

      • Environment.getExternalStorageDirectory() 为您提供外部存储(SD 卡)的路径。
      • getFilesDir() 来自活动或其他上下文。提供应用内部文件存储的路径

      您也可以使用字符串文件名(没有路径,只有文件)调用openFileOutput(),这将打开 FileOutputStream 并一次性创建文件供您使用。

      希望有帮助!

      【讨论】:

        猜你喜欢
        • 2022-06-14
        • 2016-05-08
        • 1970-01-01
        • 2018-12-15
        • 1970-01-01
        • 2011-06-02
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        相关资源
        最近更新 更多