Command line progress bar in Java

前端 未结 15 2096
[愿得一人]
[愿得一人] 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:58

    I use a "bouncing" progress bar when I need to delay a tool to prevent a race condition.

    private void delay(long milliseconds) {
        String bar = "[--------------------]";
        String icon = "%";
    
        long startTime = new Date().getTime();
        boolean bouncePositive = true;
        int barPosition = 0;
    
        while((new Date().getTime() - startTime) < milliseconds) {
            if(barPosition < bar.length() && barPosition > 0) {
                String b1 = bar.substring(0, barPosition);
                String b2 = bar.substring(barPosition);
                System.out.print("\r Delaying: " + b1 + icon + b2);
                if(bouncePositive) barPosition++;
                else barPosition--;
            } if(barPosition == bar.length()) {
                barPosition--;
                bouncePositive = false;
            } if(barPosition == 0) {
                barPosition++;
                bouncePositive = true;
            }
    
            try { Thread.sleep(100); }
            catch (Exception e) {}
        }
        System.out.print("\n");
    }
    

提交回复
热议问题