繁体   English   中英

我尝试下载文件时出错

[英]Getting error when I try to download file

我在网上找到了这个源代码并对其进行了一些修改。 但我得到一个错误说: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中没有读/写权限

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

  • Environment.getExternalStorageDirectory()为您提供外部存储(SD卡)的路径。
  • 来自Activity或其他Context的getFilesDir() 提供应用程序内部文件存储的路径

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

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM