在 Android 中从 URL 保存图像时出现只读错误
我试图在 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)
任何帮助都会很棒。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
new File(fileName);
调用默认的目录不可写。要获取当前上下文的文件写入目录的路径,请使用 getFilesDir()。所以new File(getFilesDir()+fileName);
相当于在“当前”目录中打开文件的通常 java 行为。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(). Sonew File(getFilesDir()+fileName);
equates to the usual java behaviour of opening a file in the "current" directory.尝试保存到/sdcard/example.gif
try saving to /sdcard/example.gif