栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

java 文件下载进度

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 文件下载进度

一个工作示例,使用您的代码并在进度条中显示进度可能如下所示:

import java.io.BufferedOutputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.swing.JFrame;

import javax.swing.JProgressBar;

import javax.swing.SwingUtilities;

import javax.swing.WindowConstants;

public class Progressbar {

public static void main(String[] args) {

final JProgressBar jProgressBar = new JProgressBar();

jProgressBar.setMaximum(100000);

JFrame frame = new JFrame();

frame.setContentPane(jProgressBar);

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

frame.setSize(300, 70);

frame.setVisible(true);

Runnable updatethread = new Runnable() {

public void run() {

try {

URL url = new URL("http://downloads.sourceforge.net/project/bitcoin/Bitcoin/blockchain/bitcoin_blockchain_170000.zip");

HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());

long completeFileSize = httpConnection.getContentLength();

java.io.BufferedInputStream in = new java.io.BufferedInputStream(httpConnection.getInputStream());

java.io.FileOutputStream fos = new java.io.FileOutputStream(

"package.zip");

java.io.BufferedOutputStream bout = new BufferedOutputStream(

fos, 1024);

byte[] data = new byte[1024];

long downloadedFileSize = 0;

int x = 0;

while ((x = in.read(data, 0, 1024)) >= 0) {

downloadedFileSize += x;

// calculate progress

final int currentProgress = (int) ((((double)downloadedFileSize) / ((double)completeFileSize)) * 100000d);

// update progress bar

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

jProgressBar.setValue(currentProgress);

}

});

bout.write(data, 0, x);

}

bout.close();

in.close();

} catch (FileNotFoundException e) {

} catch (IOException e) {

}

}

};

new Thread(updatethread).

start();

}

}

这显示了如何做到 – 在使用之前你应该考虑GUI-Threads等.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984775.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号