从网络上下载文件到本地

下载:

 1 void downloadDemo() {
 2         String fileName = "E:" + File.separator + "test" + File.separator
 3                 + "baidu.png";
 4         URL url = null;
 5         HttpsURLConnection connection = null;
 6         File file = new File(fileName);
 7         if (!file.exists()) {
 8             try {
 9                 file.createNewFile();
10             } catch (IOException e) {
11                 // TODO Auto-generated catch block
12                 e.printStackTrace();
13             }
14         }
15         InputStream is = null;
16         OutputStream os = null;
17         byte[] b = new byte[1024];
18         int len = 0;
19         try {
20             url = new URL("https://www.baidu.com/img/bdlogo.png");
21             connection = (HttpsURLConnection) url.openConnection();
22             is = connection.getInputStream();
23             os = new FileOutputStream(file);
24             while ((len = is.read(b)) != -1) {
25                 os.write(b, 0, len);
26                //System.out.println(len);
27             }
28             System.out.println("download complete!" + file.length() + "   "
29                     + connection.getContentLength());
30         } catch (MalformedURLException e) {
31             // TODO Auto-generated catch block
32             e.printStackTrace();
33         } catch (IOException e) {
34             // TODO Auto-generated catch block
35             e.printStackTrace();
36         } finally {
37             try {
38                 is.close();
39                 os.close();
40             } catch (IOException e) {
41                 // TODO Auto-generated catch block
42                 e.printStackTrace();
43             }
44 
45         }
46     }
原文地址:https://www.cnblogs.com/mada0/p/4717771.html