Read-Only error when saving image from URL in Android

假装没事ソ 提交于 2019-12-08 09:37:31

问题


I am trying to save an image from a web URL in an android application however when I run it, the log cat throws an exception saying its "read only". I don't know whats going on.

Here is my downloader class:

  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);
        }

}
}

When I run this, this is what I get from the logcat:

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

Any help would be great. Thank you.


回答1:


try saving to /sdcard/example.gif




回答2:


The directory that the new File(fileName); call defaults to is not writeable. To get the path to the file writing directory for the current context, you use getFilesDir(). So new File(getFilesDir()+fileName); equates to the usual java behaviour of opening a file in the "current" directory.



来源:https://stackoverflow.com/questions/5315560/read-only-error-when-saving-image-from-url-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!