java 下载网络文件到本地
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public void downauthimg() throws MalformedURLException, IOException { 2 3 String url = "https://picsum.photos/300/150/?image="; 4 for (int i = 0; i <= 200; i++) { 5 int num = 0; 6 if (i == 0) { 7 num = 300; 8 } else { 9 num = 300 + i; 10 } 11 String imgurl = url + num; 12 try { 13 14 // 构造URL 15 URL weburl = new URL(imgurl); 16 // 打开连接 17 URLConnection con = weburl.openConnection(); 18 // 设置请求超时为5s 19 con.setConnectTimeout(5 * 1000); 20 // 输入流 21 InputStream is = con.getInputStream(); 22 23 // 1K的数据缓冲 24 byte[] bs = new byte[1024]; 25 // 读取到的数据长度 26 int len; 27 // 输出的文件流 28 File sf = new File("authimg"); 29 30 if (!sf.exists()) { 31 sf.mkdirs(); 32 } 33 OutputStream os = new FileOutputStream(sf.getPath() + "\\" + i + ".jpg"); 34 // 开始读取 35 while ((len = is.read(bs)) != -1) { 36 os.write(bs, 0, len); 37 } 38 // 完毕,关闭所有链接 39 os.close(); 40 is.close(); 41 42 } catch (IOException e) { 43 continue; 44 } 45 } 46 }
甘于平凡,做一个甘于平凡的人,菜米油盐,生老病死。