一个简单的java读取网页图片并保存图片的程序

class SaveImage {

    //strUrl是图片的url地址;例如:http://jprice.360buyimg.com/price/gp755374-1-1-3.png
    //strPath是图片要存储的本地地址;例如:C:\\jingdong
 public SaveImage(String strUrl,String strPath) {
     
     File file = new File(strPath);// 图片保存路径
     if(!file.exists()) file.mkdirs();
     
     OutputStream os = null;
     InputStream is = null;
     HttpURLConnection connection = null;
     URL userver = null;
     
     try {
          userver = new URL(strUrl);
          connection = (HttpURLConnection) userver.openConnection();
          connection.connect();
          is = connection.getInputStream();
         os = new FileOutputStream(file.toString()+strUrl.substring(strUrl.lastIndexOf('/'), strUrl.length()));
         int b = is.read();
         while (b != -1) {
              os.write(b);
              b = is.read();
          }
         is.close();
         os.close();
         //System.out.println("图片保存成功");
     } catch (Exception e) {
      e.printStackTrace();
      System.out.println(e);
  }
 }

}

 

posted @ 2013-01-11 16:21  AndyDHG  阅读(901)  评论(0编辑  收藏  举报