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

105 篇文章 5 订阅

        分享一个通过原生的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();
                }
            }
 
        }
    }
}


————————————————
版权声明:本文为CSDN博主「邻家小妹妹」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_60499221/article/details/128531947

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值