📄 download.java
字号:
//创建于2007-11-22 by刘浩
//最后更改于2008-01-01 by兰冲
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;
//负责一个具体任务的下载 runable
//本类实现从一个URL下载一个文件,保存到指定路径,并以指定文件名保存的功能
class Download extends Observable implements Runnable {
// 最大的缓冲区大小
private static final int MAX_BUFFER_SIZE = 1024;
// 状态名称
public static final String STATUSES[] = {"下载",
"暂停", "完成", "取消", "错误"};
// 这些是状态编码
public static final int DOWNLOADING = 0;
public static final int PAUSED = 1;
public static final int COMPLETE = 2;
public static final int CANCELLED = 3;
public static final int ERROR = 4;
private URL url; // 下载url
private String dir; //下载文件保存目录
private String fileName; //保存文件名
private String fullFilePath; //文件下载后的完整路径
private int size; // 下载文件的大小(单位为字节)
private int downloaded; // 已下载字节数
private int status; // 当前下载状态
//Download的构造函数
public Download(URL url, String dir, String fileName) {
this.url = url;
this.dir = dir;
this.fileName = fileName;
if (!this.dir.endsWith("\\"))
this.dir = this.dir + "\\";
this.fullFilePath = this.dir + fileName;
File file = new File(fullFilePath);
if ( file.exists())
{
JOptionPane.showMessageDialog(null,
"待下载文件已存在", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
else
{
try
{
file.createNewFile();
}
catch( IOException e)
{
JOptionPane.showMessageDialog(null,
"创建文件失败", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
size = -1;
downloaded = 0;
status = DOWNLOADING;
//开始下载
download();
}
// 返回下载任务的下载地址
public String getUrl() {
return url.toString();
}
private String getFileName()
{
return fileName;
}
// 返回下载文件的大小
public int getSize() {
return size;
}
// 返回下载任务的完成百分比
public float getProgress() {
return ((float) downloaded / size) * 100;
}
// 返回下载状态码
public int getStatus() {
return status;
}
// 暂停当前下载
public void pause() {
status = PAUSED;
stateChanged();
}
// 恢复当前下载
public void resume() {
status = DOWNLOADING;
stateChanged();
download();
}
// 取消当前下载
public void cancel() {
status = CANCELLED;
stateChanged();
}
// 标记当前下载任务发生错误,通知观察者
private void error() {
status = ERROR;
stateChanged();
}
// 开始或恢复下载
private void download() {
Thread thread = new Thread(this);
thread.start();
}
// 下载文件
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// 打开到URL的连接
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// 标明要下载文件的哪个部分
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// 连接到服务器
connection.connect();
// 确定连接成功
if (connection.getResponseCode() / 100 != 2) {
error();
}
// 检查待下载的内容长度
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
/* 如果下载文件的大小没有设定,设置其大小 */
if (size == -1) {
size = contentLength;
stateChanged();
}
//打开文件,并将文件读写指针定位到文件末尾
file = new RandomAccessFile(fullFilePath, "rw");
file.seek(downloaded);
stream = connection.getInputStream();
byte buffer[] = new byte[MAX_BUFFER_SIZE];
while (status == DOWNLOADING) {
/* 缓冲字节数组 */
/*if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}*/
// 从服务器读数据到缓冲中
int read = stream.read(buffer);
if (read == -1)
break;
// 将缓冲写到文件中
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* 当执行到这里时设置下载任务的状态为已完成 */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
// 关闭文件
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
// 关闭到服务器的连接
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
// 通知observers本download的状态已经改变.
private void stateChanged() {
setChanged();
notifyObservers();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -