public static String downloadFile(String remoteUrl) { try { URL url = new URL(remoteUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时间为3秒 conn.setConnectTimeout(3 * 1000); //防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //文件保存位置.保存在系统临时目录 String folder = "d:/data/logs/temp/"; File dir = new File(folder); if (!dir.exists()) { dir.mkdirs(); } String fileName = getFileName(url.getPath()); File localFile = new File(dir, fileName); try ( BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(localFile)); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()) ) { int len = 1024; byte[] b = new byte[len]; while ((len = bis.read(b)) != -1) { bos.write(b, 0, len); } bos.flush(); bis.close(); conn.disconnect(); } catch (IOException e) { logger.error("### 下载文件{}发生异常。", localFile.getCanonicalPath(), e); } if (logger.isInfoEnabled()) { logger.info("### 下载文件:{}到本地:{}成功。", remoteUrl, localFile.getCanonicalPath()); } return localFile.getCanonicalPath(); } catch (IOException e) { e.printStackTrace(); } return null; } private static String getFileName(String remoteUrl) { String decode = null; try { decode = URLDecoder.decode(remoteUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File file = new File(decode); return file.getName(); }
调用:
downloadFile(url);
将远程的文件下载到本地了