1 /** 2 * 3 * @param urlPath 4 * 下載路徑 5 * @param saveDir 6 * 下載存放目錄 7 * @return 返回下載文件 8 * @throws Exception 9 */ 10 public static void downloadFile(String urlPath, String saveDir) throws Exception { 11 URL url = new URL(urlPath); 12 // 連接類的父類,抽象類 13 URLConnection urlConnection = url.openConnection(); 14 // http的連接類 15 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; 16 // 設定請求的方法,默認是GET 17 httpURLConnection.setRequestMethod("GET"); 18 // 設置字符編碼 19 httpURLConnection.setRequestProperty("Charset", "UTF-8"); 20 //狀態碼 200:成功連接 21 int code = httpURLConnection.getResponseCode(); 22 if (code == 200) { 23 System.out.println("鏈接地址成功!"); 24 } 25 InputStream inputStream = httpURLConnection.getInputStream(); 26 File file = new File(saveDir); 27 OutputStream out = new FileOutputStream(file); 28 int size = 0; 29 byte[] buf = new byte[1024]; 30 while ((size = inputStream.read(buf)) != -1) { 31 out.write(buf, 0, size); 32 } 33 inputStream.close(); 34 out.close(); 35 }