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 }