参考链接:
https://www.mkyong.com/java/java-how-to-download-a-file-from-the-internet/
1、Apache Commons IO
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
String fromFile = "ftp://ftp.arin.net/pub/stats/arin/delegated-arin-extended-latest";
String toFile = "F:\\arin.txt";
try {
// connectionTimeout, readTimeout = 10 seconds
FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 10000, 10000);
} catch (IOException e) {
e.printStackTrace();
}
2、Java NIO
String fromFile = "https://download-cf.jetbrains.com/idea/ideaIU-2018.1.6.win.zip";
String toFile = "F:\\IDEA\\ideaIU-2018.1.6.win.zip";
try {
URL website = new URL(fromFile);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(toFile);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
System.out.println("---------success----------------");
} catch (IOException e) {
e.printStackTrace();
}
static final String FILE_URL = "https://download-cf.jetbrains.com/idea/ideaIU-2018.1.6.exe";
static final String FILE_NAME = "F:\\IDEA\\ideaIU-2018.1.6.exe";
public static void main(String[] args) throws Exception {
javaIO();
}
static void javaIO() {
try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)) {
byte dataBuffer[] = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
System.out.println("read >" + bytesRead);
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
} catch (IOException e) {
// handle exception
}
}
3、多线程下载文件
package net.liuzidong.download;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 多线程下载文件
*/
public class DownloadUtil {
// 定义成员变量
private String path; // 远程资源路径
private String targetPath; // 本地存储路径
private DownFileThread[] threads; // 线程list
private int threadNum; // 线程数量
private long length; // 下载的文件大小
// 构造初始化
public DownloadUtil(String path, String targetPath, int threadNum) {
super();
this.path = path;
this.targetPath = targetPath;
this.threads = new DownFileThread[threadNum];
this.threadNum = threadNum;
}
// 多线程下载文件资源
public void download() {
URL url;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5 * 1000); // 设置超时时间为5秒
conn.setRequestMethod("GET");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("accept", "*/*");
// 获取远程文件的大小
length = conn.getContentLength();
conn.disconnect();
// 设置本地文件大小
RandomAccessFile targetFile = new RandomAccessFile(targetPath, "rw");
targetFile.setLength(length);
// 每个线程下载大小
long avgPart = length / threadNum + 1;
// 下载文件
for (int i = 0; i < threadNum; i++) {
long startPos = avgPart * i;
RandomAccessFile targetTmp = new RandomAccessFile(targetPath, "rw");
targetTmp.seek(startPos); // 分段下载
threads[i] = new DownFileThread(startPos, targetTmp, avgPart);
threads[i].start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 监控下载进度
public double getDownRate() {
int currentSize = 0;
for (int i = 0; i < threadNum; i++) {
currentSize += threads[i].length;
}
return currentSize * 1.0 / length;
}
// 定义线程类
class DownFileThread extends Thread {
private long startPos;
private RandomAccessFile raf;
private long size;
private long length;
public DownFileThread(long startPos, RandomAccessFile raf, long size) {
super();
this.startPos = startPos;
this.raf = raf;
this.size = size;
}
public void run() {
URL url;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5 * 1000); // 设置超时时间为5秒
conn.setRequestMethod("GET");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("accept", "*/*");
InputStream in = conn.getInputStream();
in.skip(this.startPos);
byte[] buf = new byte[1024];
int hasRead = 0;
while (length < size && (hasRead = in.read(buf)) != -1) {
raf.write(buf, 0, hasRead);
length += hasRead;
}
raf.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 测试
public static void main(String[] args) {
String path = "http://ftp.jaist.ac.jp/pub/eclipse/technology/epp/downloads/release/photon/R/eclipse-jee-photon-R-win32-x86_64.zip";
String targetPath = "F:\\download\\eclipse\\eclipse-jee-photon-R-win32-x86_64.zip";
final DownloadUtil download = new DownloadUtil(path, targetPath, 3);
download.download();
System.out.println("开始下载...");
// 主线程负责下载文件,在启动一个线程负责监控下载的进度
new Thread(new Runnable() {
@Override
public void run() {
while (download.getDownRate() < 1) {
try {
Thread.sleep(2000); // 200毫秒扫描一次
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("下载完成...");
}
}).start();
}
}
分享到:
相关推荐
Think Java: How to Think Like a Computer Scientist by Allen B. Downey, Chris Mayfield 2016 | ISBN: 1491929561 Currently used at many colleges, universities, and high schools, this hands-on ...
描述中提到,“This demonstrates how to retrieve the file size from a specified file”,这提示我们关注的是一个实际的代码示例或者教程,它将展示如何从给定的文件路径中获取文件的大小信息。这通常涉及到读取...
Recently, Zhongguancun Online distributed the ZOL Downer for users to download the resources from ZOL. In this case, users can just download the ZOL downer with the code of resources, not the ...
How to run a JAR file
本书是针对没有经验或没有经验的人的计算机科学和编程的简介。 它从最基本的概念开始,并在首次使用时仔细定义所有术语。
How to read a book efficiently. Part one The dimensions of reading Part two The third level of reading Part three Approaches to different kinds of reading Part four The ultimate goals of reading
Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard...
C++ How to Program presents leading-edge computing technologies in a friendly manner appropriate for introductory college course sequences, based on the curriculum recommendations of two key ...
Java How to Program, Early Objects, 11th Edition Java How to Program, Early Objects, 11th Edition Java How to Program, Early Objects, 11th Edition Java How to Program, Early Objects, 11th Edition
本书以初学者为起点,循序渐进地介绍了面向对象的Java编程语言,系统地讨论了Java的基本概念和编程技术。全书共分为18章,首先从基本的Java理论开始,讲解了Java的基本数据类型和控制结构,Java中的方法、数组和字符...
Including all source code of the book Java How to Programming(8th), which is a very classic book for Java learners.
教材是java how to program,这是第一二章的英文ppt课件
Introduction to Computers, the Internet and the World Wide Web Chapter 2. Introduction to Java Applications Chapter 3. Introduction to Classes and Objects Chapter 4. Control Statements: Part I ...