1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import lombok.extern.slf4j.Slf4j;
import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection;
@Slf4j public class FileUtil {
public static File downloadFile(String urlPath, String downloadDir) { File file = null; try { URL url = new URL(urlPath); URLConnection urlConnection = url.openConnection(); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection; httpUrlConnection.setConnectTimeout(1000 * 5); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.setRequestProperty("Charset", "UTF-8"); httpUrlConnection.connect(); int fileLength = httpUrlConnection.getContentLength();
log.info("您要下载的文件大小为:" + fileLength / (1024 * 1024) + "MB");
BufferedInputStream bin = new BufferedInputStream(httpUrlConnection.getInputStream()); String fileFullName = urlPath.substring(urlPath.lastIndexOf("/") + 1); File filePath = new File(downloadDir); if (!filePath.exists() && !filePath.isDirectory()) { log.info("目录不存在,创建目录:" + filePath); filePath.mkdir(); } file = new File(downloadDir + File.separatorChar + fileFullName); OutputStream out = new FileOutputStream(file); int size; int len = 0; byte[] buf = new byte[2048]; while ((size = bin.read(buf)) != -1) { len += size; out.write(buf, 0, size); } bin.close(); out.close(); log.info("文件下载成功!"); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); log.info("文件下载失败!"); } return file; }
public static void main(String[] args) { File file = downloadFile("http://192.168.80.97:9090/artifactory/DEV/ipipe/pipeline/1607175965084_15.tar", "E:\\down"); System.out.println(file.getName()); } }
|