下载文件的时候,如果为了用户友好,都会给予进度条提醒用户,那么怎么做呢?
其实很简单,首先获取服务器文件的大小urlConnection.getContentLength(),然后在读取文件过程计算文件百分比增长即可
/**
* 文件下载工具 by sam on 2015/11/5.
*/
public final class FileUtil {
/**
* 单线程下载文件
* @param url 文件的网络地址
* @param path 保存的文件地址
*/
public static void dowanload(String url, String path)
throws IOException {
System.out.println("下载中...");
InputStream inputStream = null;
RandomAccessFile randomAccessFile = null;
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(10 * 1000);
File file = new File(path);
if (!file.getParentFile().exists())
file.getParentFile().mkdir();
if (file.exists())
file.delete();
file.createNewFile();
int responseCode = urlConnection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
inputStream = urlConnection.getInputStream();
int len = 0;
byte[] data = new byte[4096];
int progres = 0; //用于保存当前进度(具体进度)
int maxProgres = urlConnection.getContentLength();//获取文件
randomAccessFile = new RandomAccessFile(file, "rwd");
randomAccessFile.setLength(maxProgres);//设置文件大小
int unit = maxProgres / 100;//将文件大小分成100分,每一分的大小为unit
int unitProgress = 0; //用于保存当前进度(1~100%)
while (-1 != (len = inputStream.read(data))) {
randomAccessFile.write(data, 0, len);
progres += len;//保存当前具体进度
int temp = progres / unit; //计算当前百分比进度
if (temp >= 1 && temp > unitProgress) {//如果下载过程出现百分比变化
unitProgress = temp;//保存当前百分比
System.out.println("正在下载中..." + unitProgress + "%");
}
}
inputStream.close();
System.out.println("下载完成...");
} else {
System.out.println("服务器异常...");
}
} finally {
if (null != inputStream) {
inputStream.close();
}
if (null != randomAccessFile) {
randomAccessFile.close();
}
}
}
public static void main(String[] args) throws IOException {
String path = "D:\\abc\\abc.jpg";
String url = "http://www.dowei.com/d/file/mingxing/bagua/20151105/9e88df8cd5dd243b31eff7a4f7d53f89.jpg";
FileUtil.dowanload(url, path);
}
}