ITeye博客

在java下通过url获取远端图片,保存到本地

adong · 2009-10-14 09:29 · Markdown

import java.net.;
import java.io.
;
import javax.imageio.*;
import javax.imageio.stream.ImageOutputStream;

public class GetPic {
public GetPic() {
}

  public   static   void   main(String   args)   {  
      GetPic   getPic1   =   new   GetPic();  
      getPic1.saveToFile("http://community.csdn.net/images/CSDN_logo.GIF");  
  }  

  public   void   saveToFile(String   destUrl)   {  
      FileOutputStream   fos   =   null;  
      BufferedInputStream   bis   =   null;  
      HttpURLConnection   httpUrl   =   null;  
      URL   url   =   null;  
      int   BUFFER_SIZE   =   1024;  

      byte   buf   =   new   byte;  
      int   size   =   0;  
      try   {  
          url   =   new   URL(destUrl);  
          httpUrl   =   (HttpURLConnection)url.openConnection();  
          httpUrl.connect();  
          bis   =   new   BufferedInputStream(httpUrl.getInputStream());  

          fos   =   new   FileOutputStream("e:\\haha.gif");  
          while   ((size   =   bis.read(buf))   !=   -1)   {  
              fos.write(buf,   0,   size);  
          }  
          fos.flush();  
      }  
      catch   (IOException   e)   {  
      }  
      catch   (ClassCastException   e)   {  
      }  
      finally   {  
          try   {  
              fos.close();  
              bis.close();  
              httpUrl.disconnect();  
          }  
          catch   (IOException   e)   {  
          }  
          catch   (NullPointerException   e)   {  
          }  
      }  
  }  

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。