在Android中从URL保存图像时出现只读错误
我试图在android应用程序中保存来自web URL的图像,但是当我运行它时,log cat抛出一个异常,表示其为“只读”。我不知道发生了什么事 这是我的下载类:在Android中从URL保存图像时出现只读错误,android,filenotfoundexception,urlconnection,fileoutputstream,Android,Filenotfoundexception,Urlconnection,Fileoutputstream,我试图在android应用程序中保存来自web URL的图像,但是当我运行它时,log cat抛出一个异常,表示其为“只读”。我不知道发生了什么事 这是我的下载类: public class ImageDownload { public static void downloader(String imageURL, String fileName) { try { URL url = new URL("http://www.exampleu
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)
任何帮助都会很好。谢谢。尝试保存到/sdcard/example.gif新文件(文件名)所在的目录代码>调用默认为不可写。要获取当前上下文的文件写入目录的路径,请使用GetFileDir()。所以
新文件(getFilesDir()+文件名)代码>等同于在“当前”目录中打开文件的常见java行为 好吧,完美解决了。它保存到/sdcard/example.gif。我刚刚换掉了/sdcard/和我想要的确切位置(data/data/com…),它成功了。我没有意识到我没有指定正确的文件位置。谢谢我认为它应该是新文件(getFilesDir()+File.separator+fileName)
,否则您将得到类似/data/data//files
的内容,而不是数据/data//files/