Roberto
Roberto

Reputation: 178

ProgressMonitorInputStream - progress bar doesn't show the real progress

Here's my code:

class Copy extends SwingWorker<Void, Void> {

private File selectedfile = new File("D:/Adatok/proba.file");
private File chosenDestination = new File("D:/Adatok/ide/proba.file");

@Override
protected Void doInBackground() throws Exception {
try {
     FileInputStream fileInputStream = new FileInputStream(
     selectedfile);
     BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
     ProgressMonitorInputStream progressMonitorInputStream;
     progressMonitorInputStream = new ProgressMonitorInputStream(Panel.this,"Copying...", bufferedInputStream);
     File outputFile = new File("" + chosenDestination);
     FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    int data;
    byte[] buffer = new byte[1024];
    while ((data = progressMonitorInputStream.read(buffer)) > 0) {
         bufferedOutputStream.write(buffer);
    }
    bufferedOutputStream.close();
    progressMonitorInputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

@Override
public void done() {
     JOptionPane.showMessageDialog(Panel.this, "Ready!", "Done", 1);
}
}

}

It works fine with smaller files, but if I try it with a 3GB file, the progressbar shows wrong progress. When it's 100% the copying isn't finished, in the remaining time the progress bar is set to 0% and doesn't move. What's wrong with it?

Upvotes: 1

Views: 727

Answers (1)

lemming622
lemming622

Reputation: 131

I know that this is old but I have found this thread more than once over the years while having to fix this same problem. It is a bug in Java as @Roberto has pointed out. I did a similar workaround that the bug reporter posts about.

  1. I copied the source of the ProgessMonitorInputStream and create a new class called ProgessMonitorInputStreamLongBased to avoid confusion
  2. I check the size of the file in bytes and see if it is bigger than Integer.MAX_VALUE:
    • If it is less then no change.
    • If greater then max size is the max int value and scaling will be performed.
  3. The scale is found once and it is equal to the previously found "size" divided by the real length of the file.

I hope this helps someone else who runs across this problem.

Upvotes: 1

Related Questions