package com.rj.yg; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; /** * * @author 杨刚 * 9. 异常处理 读取http://www.google.cn/intl/zh-CN/images/logo_cn.gif文件并存储于本地。 * 并尝试处理异常。比如说适当的时候拔插网线。 尝试最多不超过5次读取网络文件。如果5次都不能正常读取文件。则放弃。 * Jul 29, 2010 */ public class ReadUrlExceptionDemo { public static void main(String[] args) { String url = "http://www.google.cn/intl/zh-CN/images/logo_cn.gif"; String fileName = "image.gif"; // 读取http://www.google.cn/intl/zh-CN/images/logo_cn.gif文件并存储于本地 for (int i = 0; i < 5; i++) { boolean b = getUrlImg(url, fileName); if (b == true) { break; } } } /** * 读取http://www.google.cn/intl/zh-CN/images/logo_cn.gif文件并存储于本地 */ public static boolean getUrlImg(String urlStr, String name) { try { int httpResult; // 服务器返回的状态 URL url = new URL(urlStr); // 创建URL URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码 urlconn.connect(); HttpURLConnection httpconn = (HttpURLConnection) urlconn; httpResult = httpconn.getResponseCode(); if (httpResult == HttpURLConnection.HTTP_OK) { int filesize = urlconn.getContentLength(); // 取数据长度 System.out.println(filesize); BufferedInputStream bis = new BufferedInputStream(urlconn .getInputStream()); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(name)); byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲 int num = -1; // 读入的字节数 while (true) { num = bis.read(buffer); // 读入到缓冲区 if (num == -1) { break; // 已经读完 } bos.flush(); bos.write(buffer, 0, num); } bos.close(); bis.close(); System.out.println("图片保存成功!"); return true; } else { System.out.println("连接失败!"); } } catch (MalformedURLException e) { System.out.println("连接失败!"); } catch (FileNotFoundException e) { System.out.println("连接失败!"); } catch (IOException e) { System.out.println("连接失败!"); } return false; } }