【Java】网图下载

【Java】网图下载

需求

给定网络图片的网络链接,将图片下载到本地

步骤

  1. 导入工具类需要的工具包commons-io-版本号.jar
    导包

    • 获取方法工具包:https://commons.apache.org/proper/commons-io/download_io.cgi

    • 在项目下创建lib包,右键选择Add as library... 将其作为类库
      类库

    • 将工具包复制到该包下

  2. 编写下载工具类与下载方法,使用工具类FileUtils下的copyURLToFile方法

    FileUtils.copyURLToFile(new URL(url),new File(filename));
    
  3. 导入工具类需要的包commons-io-版本号.jar

    • 下载
  4. 编写测试类

    • 继承于Thread类,实现同时下载图片
    • 定义属性
    • 编写构造方法
    • 重写run()方法
    • 编写main方法
      • 实例化,给定地址与图片名
      • start()

完整代码

package com.cxl.demo02_load;

import org.apache.commons.io.FileUtils;
import sun.net.www.protocol.http.HttpURLConnection;

import java.io.File;
import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;

//下载测试
public class Load extends Thread{
    private String url;
    private String name;

    public Load(String url,String name)  {
        this.url = url;
        this.name = name;
    }
    

    @Override
    public void run() {
        Downloader d = new Downloader();
        try {
            d.downloder(url,name);
            System.out.println("文件名:"+name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Load l1 = new Load("https://i.rilibiao.com.cn/zb_users/upload/2021/01/1611544790_4.jpg",
                "魈.jpg");
        Load l2 = new Load("https://tse3-mm.cn.bing.net/th/id/OIP-C.oz-9w1w7nSxP1INXpm2LCgHaEK?w=330&h=185&c=7&r=0&o=5&dpr=1.3&pid=1.7",
                "温迪.jpg");

        l1.start();
        l2.start();
    }
}

//下载工具类
class Downloader {
    public void downloder(String url, String filename) throws IOException {

        //为HTTP请求标头添加一个User-Agent
//        URLConnection conn = new URL(url).openConnection();
//        conn.addRequestProperty("User-Agent",
//                "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//        conn.connect();


        FileUtils.copyURLToFile(new URL(url),new File(filename));
    }
}

//

效果

运行效果

注意

若图片源地址网站限制了资源爬取,可能报错:Server returned HTTP response code: 403 for URL

  • 可能解决方法:在编写在下载类中,为HTTP请求标头添加一个User-Agent
    URLConnection conn = new URL(url).openConnection();
    conn.addRequestProperty("User-Agent",
    	"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    conn.connect();
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java多线程下载网络图片的实现方法如下: 1. 定义一个DownloadTask类,用于表示一个下载任务,其中包含下载的URL、存储路径和线程数等信息。 2. 在DownloadTask类中实现Runnable接口,并重写run()方法,在该方法中实现下载图片的逻辑,可以使用URLConnection或者HttpClient等工具类进行网络请求,并将下载的数据写入本地文件。 3. 在DownloadTask类中定义一个download()方法,用于启动下载任务,该方法将根据线程数划分下载任务,并启动多个线程进行下载。 4. 在应用程序主方法中创建DownloadTask对象,并调用download()方法启动下载任务。 下面是一个简单的Java多线程下载网络图片的示例代码: ```java import java.io.*; import java.net.*; import java.util.concurrent.*; public class DownloadTask implements Runnable { private String url; private String file; private int threadCount; public DownloadTask(String url, String file, int threadCount) { this.url = url; this.file = file; this.threadCount = threadCount; } public void run() { try { URLConnection conn = new URL(url).openConnection(); int contentLength = conn.getContentLength(); System.out.println("Total size: " + contentLength); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.setLength(contentLength); ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { long start = (long) i * contentLength / threadCount; long end = (long) (i + 1) * contentLength / threadCount - 1; executor.execute(new DownloadThread(url, file, start, end)); } executor.shutdown(); executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES); System.out.println("Download completed."); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String url = "http://www.example.com/image.jpg"; String file = "image.jpg"; int threadCount = 4; DownloadTask task = new DownloadTask(url, file, threadCount); task.download(); } } class DownloadThread implements Runnable { private String url; private String file; private long start; private long end; public DownloadThread(String url, String file, long start, long end) { this.url = url; this.file = file; this.start = start; this.end = end; } public void run() { try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes=" + start + "-" + end); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); InputStream in = conn.getInputStream(); RandomAccessFile raf = new RandomAccessFile(file, "rw"); raf.seek(start); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { raf.write(buffer, 0, len); } raf.close(); in.close(); System.out.println("Part downloaded: " + start + "-" + end); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述代码中,DownloadTask类表示一个下载任务,其中包含下载的URL、存储路径和线程数等信息。在run()方法中实现下载图片的逻辑,将根据线程数划分下载任务,并启动多个线程进行下载。DownloadThread类表示一个下载线程,其中包含下载的URL、存储路径和下载的起始和结束位置等信息。在run()方法中实现下载数据的逻辑,使用HttpURLConnection发送请求,并将下载的数据写入本地文件。 在应用程序主方法中,创建DownloadTask对象,并调用download()方法启动下载任务。其中,url表示要下载的图片URL,file表示要保存的本地文件路径,threadCount表示下载线程数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值