我正在将文件从计算机复制到外部设备,例如SD卡,我希望在文件复制过程中取得进展。我正在使用SwingWorker,以便我可以同时复制多个文件。我不知道如何获取当前进度并将其发送到SwingWorker的publish()方法。这是我复制文件的代码:
FileInputStream finStream = new FileInputStream(sourceFile);
FileOutputStream foutStream = new FileOutputStream(destFile);
/*
* Adapted from http://www.java2s.com/Code/Java/File-Input Output/UseBufferedInputStreamandBufferedOutputStreamtocopybytearray.html
*/
BufferedInputStream bufIS = new BufferedInputStream(finStream);
BufferedOutputStream bufOS = new BufferedOutputStream(foutStream);
byte[] byteBuff = new byte[32 * 1024];
int len;
while ((len = bufIS.read(byteBuff)) > 0){
bufOS.write(byteBuff, 0, len);
publish(/*What do I put here?*/);
}
bufIS.close();
bufOS.close();
答案 0 :(得分:0)
注意:写入的数据可能是缓冲区,并将根据分配的缓冲区大小进行刷新(但这不应妨碍计算)。
答案 1 :(得分:0)
Swingworker已经有一个"进度功能",用它代替publish/process
long size = file.length();
int count = 0;
int progress;
while ((len = bufIS.read(byteBuff)) > 0) {
...
count += len;
if (size > 0L) {
progress = (int) ((count * 100) / size);
setProgress(progress);
}
}
然后,您可以worker.getProgress()
使用EDT
或使用progressBar或其他任何
PropertyChangeListener
E.g:
public class MyWorker extends SwingWorker<Void, Void> implements PropertyChangeListener {
public MyWorker() {
addPropertyChangeListener(this);
}
....
/* Your code */
....
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
myProgressBar.setValue((Integer) evt.getNewValue());
}
}
}
或
MyWorker worker = new MyWorker();
worker.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
myProgressBar.setValue((Integer) evt.getNewValue());
}
}
}
如果您更喜欢publish/process
然后public class MyWorker extends SwingWorker<Void, Integer>
,则可以使用整数调用publish