java下载pdf等静态文件

java下载pdf等静态文件

 
 
package com.example.climbnumber;
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;

public class Test02 {

    public static void main(String[] args) {
        try {
            download("https://disclosure.shcpe.com.cn//cpec-ent/file/20220508/1652002109174%E6%88%AA%E8%87%B32022%E5%B9%B44%E6%9C%8830%E6%97%A5%E6%8C%81%E7%BB%AD%E9%80%BE%E6%9C%9F%E5%90%8D%E5%8D%95.pdf", "C:\\Users\\13560\\Desktop\\12.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载文件到本地
     * @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();
        }
    }
}
posted @ 2023-04-22 19:05  binbinx  阅读(425)  评论(0编辑  收藏  举报