Android 尝试下载文件时出错

Android 尝试下载文件时出错,android,file,download,Android,File,Download,我在网上找到了这个源代码,并对它做了一些修改。但是我得到一个错误:java.io.FileNotFoundException/data/datafile.zip。 我应该怎么做才能让它运行?我必须先创建文件吗 谢谢,西格德 private Thread checkUpdate = new Thread() { public void run() { try { long startTime = System.currentTimeMillis();

我在网上找到了这个源代码,并对它做了一些修改。但是我得到一个错误: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);
        }
    }
};

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


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

  • Environment.getExternalStorageDirectory()
    提供外部存储(SD卡)的路径
  • getFilesDir()
    来自活动或其他上下文。提供应用程序内部文件存储的路径
您还可以使用字符串文件名调用
openFileOutput()
,这将打开FileOutputStream并一次性创建文件供您使用

希望有帮助