Reputation: 67
I'm trying to figure out how to make a JProgressBar fill up as a file is being read. More specifically I need to read in 2 files and fill 2 JProgressBars, and then stop after one of the files has been read.
I am having trouble understanding how to make that work with a file. With two threads I would just put a for(int i = 0; i < 100; i++)
loop and setValue(i)
to get the current progress. But with files I don't know how to set the progress. Maybe get the size of the file and try something with that? I am really not sure and was hoping someone could throw and idea or two my way.
Thank you!
Update for future readers:
I managed to solve it by using a file.length()
which returned the size of the file in bytes, then setting the bar to go from 0 to that size instead of the regular 100, and then using
for(int i = 0; i < fileSize; i++)
To get the bar loading like it should.
Upvotes: 3
Views: 130
Reputation: 517
Example usage of ProgressMonitorInputStream. It automatically display simple dialog with progressbar if reading from InputStream takes longer - you can adjust that time by using: setMillisToPopup, setMillisToDecideToPopup.
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setSize(640, 480);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
mainFrame.setVisible(true);
String filename = "Path to your filename"; // replace with real filename
File file = new File(filename);
try (FileInputStream inputStream = new FileInputStream(file);
ProgressMonitorInputStream progressInputStream = new ProgressMonitorInputStream(mainFrame, "Reading file: " + filename, inputStream)) {
byte[] buffer = new byte[10]; // Make this number bigger - 10240 bytes for example. 10 is there to show how that dialog looks like
long totalReaded = 0;
long totalSize = file.length();
int readed = 0;
while((readed = progressInputStream.read(buffer)) != -1) {
totalReaded += readed;
progressInputStream.getProgressMonitor().setNote(String.format("%d / %d kB", totalReaded / 1024, totalSize / 1024));
// Do something with data in buffer
}
} catch(IOException ex) {
System.err.println(ex);
}
}
Upvotes: 2