0

我正在尝试从 android 应用程序中的 Web URL 保存图像,但是当我运行它时,日志猫会抛出一个异常,说它是“只读的”。我不知道发生了什么事。

这是我的下载器类:

  public class ImageDownload {

public static void downloader(String imageURL, String fileName) { 
        try {
                URL url = new URL("http://www.exampleurl.com/" + imageURL); 
                File file = new File(fileName);


                URLConnection con = url.openConnection();

                InputStream is = con.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

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

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();

        } catch (IOException e) {
                Log.d("Downloader", "Error: " + e);
        }

}
}

当我运行它时,这是我从 logcat 得到的:

DEBUG/Downloader(22112): Error: java.io.FileNotFoundException: /example.gif (Read-only file system)

任何帮助都会很棒。谢谢你。

4

2 回答 2

5

调用默认的目录new File(fileName);是不可写的。要获取当前上下文的文件写入目录的路径,请使用 getFilesDir()。所以new File(getFilesDir()+fileName);等同于在“当前”目录中打开文件的常见 java 行为。

于 2011-03-22T04:17:13.957 回答
3

尝试保存到 /sdcard/example.gif

于 2011-03-15T17:29:09.597 回答