JAVA通过HTTP协议下载网络文件

        分享一个通过原生的Java代码下载网络资源文件方法,使用URL类连接上网络服务器通过多线程使用I/O流的方式下载文件。

流程:

  • 获取到资源的大小及各项参数
  • 使用RandomAccessFile类生成对应大小的文件用于防止空间不足
  • 启动下载任务线程,传入线程号等参数
  • 下载线程与服务器建立连接,获取到对应的I/O流,将传入的字节写入到下载的本地文件中

线程工作示意图:

代码部分:

主程序

import jdk.management.resource.NotifyingMeter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicLong;

public class Download{

    public static void main(String[] args) throws IOException {
        //1.待下载文件大小
        String url="http://dl.baofeng.com/baofeng5/bf5_new.exe";
        long fileSize=getFileSize(url);
        System.out.println("下载的文件大小:"+fileSize);
        String newFileName=getNewFileName(url);
        System.out.println(newFileName);
        String newFilePath=getNewFilePath(newFileName);
        System.out.println(newFilePath);
        //创建空文件
        createNewFile(fileSize,newFilePath);
        //获取cpu数
        int threadSize=Runtime.getRuntime().availableProcessors();
        //计算每个线程要下载的大小
        long sizePerThread=getSizePerThread(threadSize,fileSize);
        System.out.println("共"+threadSize+"个线程,每个线程下载最多:"+sizePerThread+"个字节");

        for (int i=0;i<threadSize;i++){
            DownloadTaske task=new DownloadTaske(i,fileSize,threadSize,sizePerThread,url,newFilePath);
            Thread t=new Thread(task);
            t.start();
        }

        System.out.println("主线程完成");
    }

    /**
     * 获取文件大小
     * @param url
     * @return
     */
    public static long getFileSize(String url){
        long fileSize=0;
        try {
            URL u=new URL(url);
            HttpURLConnection con= (HttpURLConnection) u.openConnection();
            con.setRequestMethod("HEAD");//请求行:HEAD/xxxHTTP/1.1
            fileSize=con.getContentLength();//获取响应的大小
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileSize;
    }

    /**
     * 生成文件
     * @param url
     * @return
     */
    public static String getNewFileName(String url){
        Date date=new Date();
        DateFormat df=new SimpleDateFormat("yyyyMMddHHmmss");
        String prefix=df.format(date);

        //后缀名
        String suffix=url.substring(url.lastIndexOf("."));
        return prefix+suffix;
    }

    /**
     * 本地文件保存路径
     * @param newFileName
     * @return
     */
    public static String getNewFilePath(String newFileName){
        String userhome="H:\\迅雷下载\\"+ File.separator +newFileName;
        return userhome;
    }

    /**
     * 创建新文件
     * @param fileSize
     * @param newfilePath
     * @return
     * @throws IOException
     */
    public static void createNewFile(long fileSize,String newfilePath) throws IOException {
        RandomAccessFile raf=new RandomAccessFile(newfilePath,"rw");
        raf.setLength(fileSize);
        raf.close();
    }

    /**
     * 计算每个线程要下载的大小
     * @param threadSize
     * @param fileSize
     * @return
     */
    public static long getSizePerThread(int threadSize,long fileSize){
        return fileSize%threadSize==0?fileSize/threadSize:fileSize/threadSize+1;
    }
}

 下载任务类

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadTaske implements Runnable{
    private int i;
    private long fileSize;
    private int threadSize;
    private long sizePerThread;
    private String url;
    private String newFilePath;

    public DownloadTaske(int i, long fileSize, int threadSize, long sizePerThread, String url, String newFilePath) {
        this.i = i;
        this.fileSize = fileSize;
        this.threadSize = threadSize;
        this.sizePerThread = sizePerThread;
        this.url = url;
        this.newFilePath = newFilePath;
    }

    @Override
    public void run() {
        long start=i*sizePerThread;
        long end=(i+1)*sizePerThread-1;
        RandomAccessFile raf=null;
        InputStream iis=null;
        long total=end-start;

        try {
            raf=new RandomAccessFile(newFilePath,"rw");
            raf.seek(start);

            URL urlobj=new URL(url);

            HttpURLConnection con= (HttpURLConnection) urlobj.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty("Range","bytes="+start+"-"+end);
            con.setConnectTimeout(10*1000);
            con.connect();

            //开始下载
            iis=new BufferedInputStream(con.getInputStream());
            byte[] bs=new byte[1024*100];
            int length=0;
            while ((length=iis.read(bs,0,bs.length))!=-1){
                raf.write(bs,0,length);
            }
            System.out.println("线程:"+i+"完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (iis!=null){
                try {
                    iis.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (raf!=null){
                try {
                    raf.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    }
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
回答: 在Java中,可以使用HttpURLConnection或HttpClient来实现HTTP文件下载。下面是一个使用HttpURLConnection的示例代码: ```java String fileUrl = "http://example.com/file.doc"; String savePath = "path/to/save/file.doc"; URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); FileOutputStream outputStream = new FileOutputStream(savePath); byte\[\] buffer = new byte\[4096\]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("文件下载成功!"); } else { System.out.println("文件下载失败,错误码:" + responseCode); } ``` 这段代码通过创建一个URL对象,并使用HttpURLConnection打开连接。然后,通过输入流读取服务器返回的数据,并将数据写入到本地文件中。最后,关闭输入流和输出流,完成文件下载。请注意,你需要替换`fileUrl`和`savePath`为你实际的文件URL和保存路径。 #### 引用[.reference_title] - *1* [JAVA 实现 HTTP文件下载](https://blog.csdn.net/yangsen251024/article/details/8613150)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JAVA通过HTTP协议下载网络文件](https://blog.csdn.net/m0_60499221/article/details/128531947)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邻家小妹妹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值