JDK中http协议下载文件简单示例

本文提供了一个使用HTTP协议下载文件的Java类实现。该类通过指定URL、本地文件名和保存目录来初始化,并利用HttpURLConnection进行网络连接,进而将远程文件下载到指定路径。

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

 http协议下载文件代码:
  1. public class HttpDownload {
  2.     private final int  BUF_SIZE = 8096;
  3.     
  4.     private String strUrl = null;
  5.     
  6.     private String localFile = null;
  7.     
  8.     private String localDir = null;
  9.     
  10.     private URL url = null;
  11.     
  12.     private HttpURLConnection httpConn = null;
  13.     
  14.     private boolean debug = true;
  15.     
  16.     public HttpDownload() {
  17.         
  18.     }
  19.     
  20.     public HttpDownload(String url, String file, String dir) throws IOException {
  21.         strUrl = url;
  22.         localFile = file;
  23.         localDir = dir;
  24.         init();
  25.     }
  26.     
  27.     private void init() throws IOException {
  28.         url = new URL(strUrl);
  29.         httpConn = (HttpURLConnection)url.openConnection();
  30.     }
  31.     
  32.     public void download() throws IOException   {
  33.         BufferedInputStream bis = null;
  34.         FileOutputStream fos = null;
  35.         int size = 0;
  36.         byte[] buf = new byte[BUF_SIZE];
  37.         httpConn.connect();
  38.         bis = new BufferedInputStream(httpConn.getInputStream());
  39.         fos = new FileOutputStream(localDir + File.separator + localFile);
  40.         if (debug) {
  41.             System.out.println("retreiving the file");
  42.         }
  43.         System.out.println("starting download.");
  44.         while((size = bis.read(buf)) != -1) {
  45.             fos.write(buf, 0, size);
  46.         }
  47.         fos.close();
  48.         bis.close();
  49.         httpConn.disconnect();
  50.         System.out.println("download finish.");
  51.     }
  52.   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值