Java常用代码

1. 下载网络图片

 1 public void download(String strUrl, String filename){
 2     try{
 3         URL url = new URL(strUrl);
 4         HttpURLConnection  conn = (HttpURLConnection) url.openConnection();
 5         conn.setConnectTimeout(5*1000);  
 6         conn.connect();
 7         InputStream in = conn.getInputStream();
 8         
 9         OutputStream out = new FileOutputStream(new File(filename));
10         
11         byte[] buf = new byte[1024];
12         int len = 0;
13         while((len = in.read(buf)) != -1){
14             out.write(buf, 0, len);
15         }
16         in.close();
17         out.close();
18         System.out.println(filename + "下载成功");
19     }catch(Exception e){
20         System.out.println(filename + "下载失败");
21     }
22 }
View Code
原文地址:https://www.cnblogs.com/lhat/p/7805117.html