Search code examples
javajprogressbar

How to measure task progress and update it using JProgressBar


I want to display the percentage of the task completed. But since the length of the task depends on the amount of data there is to be read from a file I can not hard code the value for pb3.setValue(...) like I am doing it now. I know I can use setIntermediate(true) to display that the task is in progress, but is there any way of determining the exact task progress basing on the size of a file.

This is the operation that I am trying to measure, where fileArray[2] is a text file I select through the JFileChooser.

BufferedReader br3 = new BufferedReader(new FileReader(fileArray[2]));
String line;

    while ((line = br3.readLine()) != null) {

        StringBuffer sb3 = new StringBuffer(br3.readLine());
            progress += 1;
            Thread.sleep(10);
            pb3.setValue(Math.min(progress, 100));
        sb3.reverse();
        bwr3.write(sb3.toString());
            txt3.append(sb3.toString());

    }

Thanks in advance for any help or suggestions.


Solution

  • Try this:

    BufferedReader br1 = new BufferedReader(
                new FileReader(fileArray[1]));
    
    while ((line = br1.readLine()) != null) {
    
        StringBuffer sb1 = new StringBuffer(
                br1.readLine());
        sb1.reverse();
        String lineReversed = sb1.toString();
    
        byte[] bytesRead = lineReversed.getBytes();
    
        for (int i = 0; i < bytesRead.length; i++) {
            totalBytesRead = totalBytesRead
                    + bytesRead[i];
        }
    }
    
    
    BufferedReader br1n = new BufferedReader(
            new FileReader(fileArray[1]));
    
    int totalBytesReadNow = 0;
    int progress = 0;
    
    while ((line = br1n.readLine()) != null) {
    
        StringBuffer sb1n = new StringBuffer(
                br1n.readLine());
    
        sb1n.reverse();
    
        String lineReversed = sb1n.toString();
    
        byte[] bytesReadNow = lineReversed.getBytes();
    
        for (int i = 0; i < bytesReadNow.length; i++) {
            totalBytesReadNow = totalBytesReadNow
                    + bytesReadNow[i];
    
            if (totalBytesReadNow >= totalBytesRead * 0.01) {
                progress = progress + 1;
                totalBytesReadNow = 0;
            }
    
            pb2.setValue(Math.min(progress, 100));
        }
    
        bwr1.write(lineReversed + "\n");
        txt2.append(lineReversed);
        Thread.sleep(0, 1);
    
    }
    
    bwr1.flush();
    bwr1.close();
    br1n.close();
    br1.close();