package Kj;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.GZIPInputStream;
/**
* 下载 工具类
*
* @author wuming
*/
public class Demo1 {
/**
* 下载文件到本地
* @author wuming
* @date 2021年11月23日 上午19:20:05
* @param urlString
* @param filename
* @throws Exception
*/
public static void download(String urlString, String filename) throws Exception {
URL url = new URL(urlString);// 构造URL
URLConnection con = url.openConnection();// 打开连接
InputStream is = con.getInputStream();// 输入流
String code = con.getHeaderField("Content-Encoding");
if ((null != code) && code.equals("gzip")) {
GZIPInputStream gis = new GZIPInputStream(is);
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = gis.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
gis.close();
os.close();
is.close();
} else {
// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}
}
public static void main(String[] args) {
try {
// download("https://img.vgc.cn/dc/file/bigpic/2019-08-16/06/06494614368.jpg", "D:\\wg\\xiazia\\pic_txt_xiazia\\10.jpg");
// download("https://pcclient.download.youku.com/youkuclient/youkuclient_setup_8.0.9.11050.exe?spm=a2hcb.25507605.product.1&file=youkuclient_setup_8.0.9.11050.exe", "D:\\wg\\xiazia\\pic_txt_xiazia\\1.exe");
download(" https://www.cs.tsinghua.edu.cn/__local/4/A5/88/41B9242401AE4D1F19EA8519BB5_0EDFFEE5_34804.pdf", "D:\\wg\\xiazia\\pic_txt_xiazia\\55.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}
//去D:\\wg\\xiazia\\pic_txt_xiazia看,完成。