我有一个类,用于从网站下载大文件并使用 jProgressBar 显示进程。 我正在使用 SwingWorker 类和 doInBackground 方法。它工作正常,但是当下载文件的大小 > 20mb 时,我收到 java.lang.IllegalArgumentException:该值应该从 0 到 100。我做错了什么?请帮我!我的一段代码:
@Override
protected Void doInBackground() throws Exception {
URL url = new URL(site);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int filesize = connection.getContentLength();
int totalDataRead = 0;
try (java.io.BufferedInputStream in = new java.io.BufferedInputStream(
connection.getInputStream())) {
java.io.FileOutputStream fos = new java.io.FileOutputStream(file);
try (java.io.BufferedOutputStream bout = new BufferedOutputStream(
fos, 1024)) {
byte[] data = new byte[1024];
int i;
while ((i = in.read(data, 0, 1024)) >= 0) {
totalDataRead = totalDataRead + i;
bout.write(data, 0, i);
int percent = (totalDataRead * 100) / filesize;
setProgress(percent);
}
}
}
return null;
}
}
最佳答案
经过计算,这...
int percent = (totalDataRead * 100) / filesize;
对我来说只是看起来不对(这可能只是我可怜的数学大脑),但在 40mb 中大约 20.48mb(或 51%)时,它会恢复为负数(-51%)
但是,如果我使用
int percent = Math.round(((float)count / (float)range) * 100f);
效果很好。
此外,我会考虑使用 filesize
和 totalDataRead
long
而不是 int
,但这只是我的想法.
还有一个可运行的示例,我用它来测试它......
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JProgressBar pb;
public TestPane() {
pb = new JProgressBar();
setLayout(new GridBagLayout());
add(pb);
SwingWorker worker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
int range = 40 * (1024 * 1024);
for (int count = 0; count < range; count += 1024) {
int percent = Math.round(((float)count / (float)range) * 100f);
setProgress(percent);
Thread.sleep(1);
}
return null;
}
};
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (null != evt.getPropertyName()) {
switch (evt.getPropertyName()) {
case "progress":
pb.setValue(worker.getProgress());
break;
}
}
}
});
worker.execute();
}
}
}
关于java - SwingWorker异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222338/