public void savePicture(URLConnection conn){
try {
if(conn == null){
throw new Exception("Can't get URLConnection.");
}
ImageInputStream iis = (ImageInputStream )conn.getContent();// 这里出 java.lang.ClassCastException 异常
FileOutputStream fos = new FileOutputStream("E:\\query\\tset.jpg");
byte[] imgBytes = null;
iis.read(imgBytes);
fos.write(imgBytes);
fos.flush();
fos.close();
iis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我相同过 URLConnection 类来访问广域网,并且能根据我给定的URL来返回这个URLConnection然后我从这个连接里面取出我访问的url的内容。
上面这个方法的参数conn是我已经连接好了的对象,在测试文本信息下载(也就是我直接把内容存成本地txt格式的文件)时是可以正常运行的,后来我想到要是访问网上的图片信息的话是不是可以,如上修改代码,但是在注释的部分却出现了类型转换的异常。图片的连接是 http://d1.sina.com.cn/200903/11/168512_whh_950_450.jpg 。
conn.getContentType() 返回的类型是 image/jpeg , 我该怎么把这个url的图片存储到本地呢?
try {
if(conn == null){
throw new Exception("Can't get URLConnection.");
}
ImageInputStream iis = (ImageInputStream )conn.getContent();// 这里出 java.lang.ClassCastException 异常
FileOutputStream fos = new FileOutputStream("E:\\query\\tset.jpg");
byte[] imgBytes = null;
iis.read(imgBytes);
fos.write(imgBytes);
fos.flush();
fos.close();
iis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
我相同过 URLConnection 类来访问广域网,并且能根据我给定的URL来返回这个URLConnection然后我从这个连接里面取出我访问的url的内容。
上面这个方法的参数conn是我已经连接好了的对象,在测试文本信息下载(也就是我直接把内容存成本地txt格式的文件)时是可以正常运行的,后来我想到要是访问网上的图片信息的话是不是可以,如上修改代码,但是在注释的部分却出现了类型转换的异常。图片的连接是 http://d1.sina.com.cn/200903/11/168512_whh_950_450.jpg 。
conn.getContentType() 返回的类型是 image/jpeg , 我该怎么把这个url的图片存储到本地呢?
按字节操作,试下,不能保证行。
try {
if(conn == null){
throw new Exception("Can't get URLConnection.");
}
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(fullPath);
byte[] b = new byte[length];
int len = 0;
while(len != -1){
fos.write(b,0,len);
len = is.read(b);
}
fos.flush();
fos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
最后还是用了分段读取流的方法,上面是具体解决的代码。
原来远程流并不是一次性创建完成,他也是需要下载的,所以,如果直接向read中传个比特数组,并要求其一次性传输完毕是不行的,即,is.read(bytes); 只能得到部分的数据,因为此事只下载了这么多,其他的还没有下载完成,流内部开始下载另一组数据,可是这个时候我们的read方法却已经结束了,就导致了我们读取的数据不全。
用上面分段限制的方法就好了。
public static String saveImage(String imagePath,String fileName) {
try {
URL url = null;
try {
url = new URL(imagePath);
} catch (Exception e) {
System.out.println("ImageError URL ERROR");
return null;
}
FilterInputStream in = (FilterInputStream) url.openStream();
File fileOut = new File(fileName);
FileOutputStream out = new FileOutputStream(fileOut);
byte[] bytes = new byte[1024];
int c;
while ((c = in.read(bytes)) != -1) {
out.write(bytes, 0, c);
}
in.close();
out.close();
return fileName;
} catch (Exception e) {
System.out.println("ImageError 图片保存失败Error!" + e.toString());
return null;
}
}