这里以下载迅雷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"));
}
}
下载下来的程序运行也没有问题: