Java下載HTTP URL連結示例
阿新 • • 發佈:2018-12-25
這裡以下載迅雷U享版為例。
示例程式碼:
package com.zifeiy.snowflake.handle.filesget; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class HttpFileGetter { public boolean download(String urlString, File localFile) { try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.setConnectTimeout(5*1000); InputStream inputStream = connection.getInputStream(); byte[] byteArr = new byte[1024]; int len; File dir = localFile.getParentFile(); if (dir.exists() == false) dir.mkdirs(); OutputStream outputStream = new FileOutputStream(localFile); while ((len = inputStream.read(byteArr)) != -1) { outputStream.write(byteArr, 0, len); } outputStream.close(); inputStream.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; } // main for test public static void main(String[] args) { HttpFileGetter httpFileGetter = new HttpFileGetter(); httpFileGetter.download("http://down.sandai.net/ThunderVIP/ThunderVIP-xlgw.exe", new File("D:\\test_download.exe")); } }
下載下來的程式執行也沒有問題: