【问题标题】:Read-Only error when saving image from URL in Android从 Android 中的 URL 保存图像时出现只读错误
【发布时间】:2011-03-15 17:26:59
【问题描述】:

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

这是我的下载器类:

  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)

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

【问题讨论】:

标签: android filenotfoundexception urlconnection fileoutputstream


【解决方案1】:

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

【讨论】:

  • 我认为应该是new File(getFilesDir() + File.separator + fileName),否则你会得到/data/data/<apk>/files<fileName>而不是data/data/<apk>/files/<fileName>
【解决方案2】:

尝试保存到 /sdcard/example.gif

【讨论】:

  • 好的,完美解决了。它保存到 /sdcard/example.gif。我刚刚用我想要的确切位置(数据/数据/com ...)换出了 /sdcard/ 并且它起作用了。我没有意识到我没有指定正确的文件位置开始。谢谢!
猜你喜欢
  • 2015-04-05
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 2015-11-22
  • 1970-01-01
相关资源
最近更新 更多