Java使用URLConnection实现网上图片下载到本地

如何从网上的一个URL地址下载文件到本地?本文章就给你答案。

例子:程序实现一个多线程下载工具类。

废话不多说直接上代码。

package com.future.net;

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

/** @Description:
 * @Author:future
 * @Date:2020/5/31/19:26
 * @Param 
 * @return 
 */
public class DownUtil {

    // 定义资源下载路径
    private String path;

    // 文件下载位置
    private String targetFile;

    // 定义需要多少个线程来下载文件
    private int threadNum;

    // 定义线程下载对象
    private DownThread[] threads;

    // 文件下载的大小
    private int fileSize;

    public DownUtil(String path, String targetFile, int threadNum) {
        this.path = path;
        this.targetFile = targetFile;
        this.threadNum = threadNum;
        // 初始化线程数组
        this.threads = new DownThread[threadNum];
    }

    /* @Description:
     * @Author:wrb
     * @Date:2020/5/31/19:33
     * @Param 
     * @return void
     */
    public void download() throws IOException {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5*1000);
        conn.setRequestMethod("GET");

        // 设置通用的请求属性
        conn.setRequestProperty(
                "Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        +"application/x-shockwave-flash, application/xaml+xml,"
                        + "application/vnd.ms-xpsdocument,application/x-ms-xbap,"
                        + "application/x-ms-application, application/vnd.ms-excel,"
                        + "application/vnd.ms-powerpoint, application.msword, */**");
        conn.setRequestProperty("Accept-Language","zh-CH" );
        conn.setRequestProperty("Charset","UTF-8" );
        conn.setRequestProperty("Connection","Keep-Alive" );

        // 获取文件大小
        fileSize = conn.getContentLength();

        conn.disconnect();

        int currentPartSize = fileSize/threadNum+1;

        RandomAccessFile file = new RandomAccessFile(targetFile,"rw" );

        // 设置本地文件大小
        file.setLength(fileSize);

        file.close();

        for (int i=0;i<threadNum;i++){
            // 每个线程下载的开始位置
            int startPos = i*currentPartSize;

            // 每个线程使用RandomAccessFile进行下载
            RandomAccessFile currentPart = new RandomAccessFile(targetFile,"rw" );

            // 设置开始下载位置
            currentPart.seek(startPos);

            // 创建下载线程
            threads[i] = new DownThread(startPos,currentPartSize ,currentPart );

            // 启动下载线程
            threads[i].start();
        }

    }

    // 获取下载的完成百分比
    public double getCompletRate(){
        int sumSize = 0;

        for (int i=0;i<threadNum;i++){

            sumSize += threads[i].length;
        }
        return sumSize*1.0/fileSize;
    }

    /** @Description:
     * @Author:下载线程
     * @Date:2020/5/31/19:45
     * @Param 
     * @return 
     */
    private class DownThread extends Thread {

        // 当前线程的下载位置
        private int startPos;

        // 当前线程负责下载的文件大小
        private int currentPartSize;

        private RandomAccessFile currentPart;

        // 当前线程已下载的字节数
        public int length;

        public DownThread(int startPos, int currentPartSize, RandomAccessFile currentPart) {
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentPart = currentPart;
        }

        @Override
        public void run() {
            try {
                URL url = new URL(path);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setConnectTimeout(5*1000);

                conn.setRequestMethod("GET");

                conn.setRequestProperty(
                        "Accept",
                        "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                                +"application/x-shockwave-flash, application/xaml+xml,"
                                + "application/vnd.ms-xpsdocument,application/x-ms-xbap,"
                                + "application/x-ms-application, application/vnd.ms-excel,"
                                + "application/vnd.ms-powerpoint, application.msword, */**");
                conn.setRequestProperty("Accept-Language","zh-CH" );
                conn.setRequestProperty("Charset","UTF-8" );
                InputStream inStream = conn.getInputStream();

                // 跳过startPos个字节,表妹当前线程只下载自己负责的那部分
                inStream.skip(this.startPos);
                byte[] buffer = new byte[1024];
                int hasRead = 0;

                // 读取网络数据,并写入本地文件
                while (length<currentPartSize && (hasRead=inStream.read(buffer))!=-1){
                    currentPart.write(buffer,0,hasRead);
                    // 累计线程下载的总大小
                    length += hasRead;
                }
                currentPart.close();
                inStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

}

测试类

测试从网上下载个图片到本地(图片:https://img-ask.csdn.net/upload/201710/31/1509412195_421436.jpg)

package com.future.net;

import java.io.IOException;

/**
 * @Author:future
 * @Date :2020/5/31/11:40
 * @Describtion:
 **/
public class MultiThreadDown {

    public static void main(String[] args) throws IOException {
        String pic1 = "https://img-ask.csdn.net/upload/201710/31/1509412195_421436.jpg";
        final DownUtil downUtil = new DownUtil(pic1,"ios.png" ,4 );
        downUtil.download();
        new Thread(()->{
            double rate = 0;
            while ((rate=downUtil.getCompletRate())<1){
                System.out.println("已完成:"+rate);
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

测试结果:

完成!!!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值