java 下載網絡文件到本地


 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     }
代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM