下载zip文件并保存到本地(JAVA)

本文介绍了一种使用Java从服务器下载ZIP文件并保存到本地的方法。具体步骤包括通过URL获取连接器、设置HTTP请求参数、创建输出流及处理文件等。提供了完整的代码示例,适用于需要批量下载文件的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此篇博客为从服务器下载zip文件然后保存到本地的记录;
1,文件下载步骤:
(1)通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)。
(2)通过HttpURLConnection设置请求参数,并发送请求,然后获取一个返 回的输入流。
(3)建立存储的目录以及保存的文件名。
(4)建立输出流并写入数据。
(5)关闭输入流和输出流。

2,代码实现:

public class HttpConnectionUtil {

    private static Logger logger = Logger.getLogger(HttpConnectionUtil.class);

    /**
     * @param urlPath     下载路径
     * @param fileSavePath 下载存放目录,包含文件名
     * @return 返回下载文件
     * @throws Exception
     */
    public static File downloadFile(String urlPath, String fileSavePath) throws Exception {

        logger.info("进入下载文件工具类");
        File file = null;
        BufferedInputStream bin = null;
        OutputStream out = null;
         HttpURLConnection httpURLConnection = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("GET");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
            httpURLConnection.connect();

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
            fileFullName = fileFullName.substring(fileFullName.lastIndexOf("/") + 1);
            logger.info("开始下载文件:" + fileFullName);
            logger.info("file length---->" + fileLength);

            url.openConnection();
			
			// 获取返回的输入流
            bin = new BufferedInputStream(httpURLConnection.getInputStream());

            file = new File(fileSavePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            //int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
               // len += size;
                out.write(buf, 0, size);
                // 打印下载百分比
               // if ((len * 100 / fileLength)>50&&(len * 100 / fileLength)<55) {
                 //   logger.info("下载了-------> " + len * 100 / fileLength + "%");
               // }else    if ((len * 100 / fileLength)>=98) {
                  //  logger.info("下载了-------> " + len * 100 / fileLength + "%");
                }
                //logger.info("下载了-------> " + len * 100 / fileLength + "%");
            }
            return file;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new CustomException(e.toString()+"文件下载异常,请检查下载链接$$"+urlPath);
        } finally {
            if (bin != null) 
                bin.close();          
            if (out != null) 
                out.close();           
            if (httpURLConnection != null) 
                httpURLConnection.close();
        }
        logger.info("下载文件结束:" + fileSavePath);
    }

}

// 主方法
public static void main(String[] args){    
	String zipUrl = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.zip";                                    
       String fileName = zipUrl.substring(zipUrl.lastIndexOf("/")); 
       //System.out.println("fileName---->"+fileName);
       String filePath = "D:\\";  
       File file = downloadFile(zipUrl , filePath + fileName);  
       System.out.println("Run ok! file " + file);  
 
}

引用自:https://www.cnblogs.com/RivenLw/p/10477458.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值