在Android中从URL保存图像时出现只读错误

Jef*_*eff 0 android urlconnection filenotfoundexception fileoutputstream

我正在尝试从Android应用程序中的Web URL保存图像,但是当我运行它时,日志cat会抛出一个异常,说它是"只读".我不知道最近发生了什么.

这是我的下载类:

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

}
}
Run Code Online (Sandbox Code Playgroud)

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

DEBUG/Downloader(22112): Error: java.io.FileNotFoundException: /example.gif (Read-only file system)
Run Code Online (Sandbox Code Playgroud)

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

Sam*_*Sam 5

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

  • 我认为它应该是`new File(getFilesDir()+ File.separator + fileName)`,否则你会得到像`/ data/data/<apk>/files <fileName>`而不是`data/data/< APK> /文件/ <filename>`. (4认同)