Command line progress bar in Java

前端 未结 15 2006
[愿得一人]
[愿得一人] 2020-11-28 01:04

I have a Java program running in command line mode. I would like to display a progress bar, showing the percentage of job done. The same kind of progress bar you would see u

15条回答
  •  情深已故
    2020-11-28 01:35

    I have made a percentage progress bare to check the remain download file.

    I call the method periodically in my file download to check the total file-size and remaining and present that in %.

    It can be used for other task purpose as well.

    Test and output example

    progressPercentage(0, 1000);
    [----------] 0%
    
    progressPercentage(10, 100);
    [*---------] 10%
    
    progressPercentage(500000, 1000000);
    [*****-----] 50%
    
    progressPercentage(90, 100);
    [*********-] 90%
    
    progressPercentage(1000, 1000);
    [**********] 100%
    

    Test with for loop

    for (int i = 0; i <= 200; i = i + 20) {
        progressPercentage(i, 200);
        try {
            Thread.sleep(500);
        } catch (Exception e) {
        }
    }
    

    The method can be easily modified:

    public static void progressPercentage(int remain, int total) {
        if (remain > total) {
            throw new IllegalArgumentException();
        }
        int maxBareSize = 10; // 10unit for 100%
        int remainProcent = ((100 * remain) / total) / maxBareSize;
        char defaultChar = '-';
        String icon = "*";
        String bare = new String(new char[maxBareSize]).replace('\0', defaultChar) + "]";
        StringBuilder bareDone = new StringBuilder();
        bareDone.append("[");
        for (int i = 0; i < remainProcent; i++) {
            bareDone.append(icon);
        }
        String bareRemain = bare.substring(remainProcent, bare.length());
        System.out.print("\r" + bareDone + bareRemain + " " + remainProcent * 10 + "%");
        if (remain == total) {
            System.out.print("\n");
        }
    }
    

提交回复
热议问题