我有以下代码,它成功地复制了一个文件。然而,它有两个问题:
startJob方法:
private void startJob(File inFile, File outFile) {
long offset = 0;
int numRead = 0;
byte[] bytes = new byte[8192];
long fileLength = inFile.length();
Boolean keepGoing = true;
progressBar.setValue(0);
try {
inputStream = new FileInputStream(inFile);
outputStream = new FileOutputStream(outFile, false);
System.out.println("Total file size to read (in bytes) : " + inputStream.available());
} catch (FileNotFoundException err) {
inputStream = null;
outputStream = null;
err.printStackTrace();
} catch (IOException err) {
inputStream = null;
outputStream = null;
err.printStackTrace();
}
if (inputStream != null && outputStream != null) {
while (keepGoing) {
try {
numRead = inputStream.read(bytes);
outputStream.write(bytes, 0, numRead);
} catch (IOException err) {
keepGoing = false;
err.printStackTrace();
}
if (numRead > 0) {
offset += numRead;
}
if (offset >= fileLength) {
keepGoing = false;
}
progressBar.setValue(Math.round(offset / fileLength) * 100);
System.out.println(Integer.toString(Math.round(offset / fileLength) * 100));
}
}
if (offset < fileLength) {
//error
} else {
//success
}
try {
inputStream.close();
outputStream.close();
} catch (IOException err) {
err.printStackTrace();
}
}发布于 2013-05-05 17:48:18
我怀疑您是在从EDT调用冗长的方法。从EDT中删除操作,例如将操作放在它自己的Runnable中,然后调用
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(value);
// or any other GUI changes you want to make
}
});否则,您的操作将阻塞EDT,直到它完成为止,并且由于EDT阻塞,任何事件(如重新绘制等)都不会被处理,->直到结束时都不会看到任何图形用户界面的更改。
发布于 2013-05-05 17:48:36
表达式Math.round(offset / fileLength)的值总是等于0 (零),因为offset < fileLength。
UPD:
如果要正确执行此计算,则必须将其更改为:
Math.round(((double)offset / (double)fileLength) * 100)https://stackoverflow.com/questions/16387244
复制相似问题