我有以下代碼成功地複製了一個文件。但是,有兩個問題是:)FileInputStream/FileOutputStream阻止?
- 的的System.out.println(在progressBar.setValue()後不打印0和100之間(間隔只是打印「0」,直到結束的地方打印「100」)
- 除了進度條的值可能由於問題#1而出錯的事實,在實際的代碼中,我也在進行其他視覺更改,但是直到整個文件才顯示被處理。我認爲FileInputStream/FileOutputStream函數是非阻塞的。如何更改以下代碼,以便在操作過程中實際更新進度欄?
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();
}
}
[不確定JProgressBar更新已無法正常工作(HTTP的可能重複://計算器。 com/questions/8812718/jprogressbar-update-not-working) – 2013-05-05 17:46:29
您是否使用[ProgressMonitorInputStream](http://docs.oracle.com/javase/7/docs/api/javax/swing/ProgressMonitorInputStream.html )?這可以爲你簡化很多工作。 – 2013-05-05 17:46:46
FileInputStream如何能夠非阻塞並仍然返回已讀取的內容? – 2013-05-05 17:47:42