URL - Android中图像文件的FileNotFoundException [英] URL - FileNotFoundException for image file in Android

查看:127
本文介绍了URL - Android中图像文件的FileNotFoundException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从特定的URL获取图像,但它会引发 FileNotFoundException 。如果我尝试从我的浏览器打开url,我可以看到图像。请帮忙。以下是我的代码谢谢。

I'm trying to get a image from particular URL but it throwsFileNotFoundException. If I try to open the url from my browser, i can see the images. Please help. Below is my code. Thanks.

String fileURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String FILENAME = "caldophilus.jpg";
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=c.getInputStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.flush();
f.close();


推荐答案

我尝试这个,它的工作正常。谢谢。

i try this and its work fine. Thanks.

URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();

这篇关于URL - Android中图像文件的FileNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆