多线程用FileUtils.copyURLToFile下载网图代码
时间: 2024-06-10 08:06:47 浏览: 173
可以实现多线程下载,提高下载速度。具体代码实现可以参考以下示例:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadDownloader {
private static final int THREAD_SIZE = 3; // 线程数
private static final String URL_PATH = "https://example.com/image.jpg"; // 要下载的文件URL路径
private static final String FILE_NAME = "image.jpg"; // 下载后保存的文件名
private static final String FILE_PATH = "D:\\"; // 下载后保存的路径
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_SIZE);
try {
URL url = new URL(URL_PATH);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
int len = conn.getContentLength();
int block = len % THREAD_SIZE == 0 ? len / THREAD_SIZE : len / THREAD_SIZE + 1;
for (int i = 0; i < THREAD_SIZE; i++) {
int start = i * block;
int end = (i + 1) * block - 1;
if (i == THREAD_SIZE - 1) {
end = len - 1;
}
Runnable task = new DownloadTask(url, start, end, FILE_PATH + FILE_NAME);
threadPool.execute(task);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
static class DownloadTask implements Runnable {
private URL url;
private int start;
private int end;
private String filePath;
public DownloadTask(URL url, int start, int end, String filePath) {
this.url = url;
this.start = start;
this.end = end;
this.filePath = filePath;
}
@Override
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(new File(filePath), "rwd");
raf.seek(start);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
raf.write(buffer, 0, len);
}
raf.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
阅读全文