Command line progress bar in Java

JavaCommand LineProgress Bar

Java Problem Overview


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 using wget under unix. Is this possible?

Java Solutions


Solution 1 - Java

I have implemented this sort of thing before. Its not so much about java, but what characters to send to the console.

The key is the difference between \n and \r. \n goes to the start of a new line. But \r is just carriage return - it goes back to the start of the same line.

So the thing to do is to print your progress bar, for example, by printing the string

"|========        |\r"

On the next tick of the progress bar, overwrite the same line with a longer bar. (because we are using \r, we stay on the same line) For example:

"|=========       |\r"

What you have to remember to do, is when done, if you then just print

"done!\n"

You may still have some garbage from the progress bar on the line. So after you are done with the progress bar, be sure to print enough whitespace to remove it from the line. Such as:

"done             |\n"

Hope that helps.

Solution 2 - Java

There is https://github.com/ctongfei/progressbar, License: MIT

Simple console progress bar. Progress bar writing now runs on another thread.

https://i.gyazo.com/1c02d51927e769cf245a108f5a8dfaf5.gif" width="600"/>

Menlo, Fira Mono, Source Code Pro or SF Mono are recommended for optimal visual effects.

For Consolas or Andale Mono fonts, use ProgressBarStyle.ASCII (see below) because the box-drawing glyphs are not aligned properly in these fonts.

https://i.gyazo.com/e01943454443f90c9499c00a6c197a41.gif" width="600"/>

Maven:

<dependency>
  <groupId>me.tongfei</groupId>
  <artifactId>progressbar</artifactId>
  <version>0.5.5</version>
</dependency>

Usage:

ProgressBar pb = new ProgressBar("Test", 100); // name, initial max
 // Use ProgressBar("Test", 100, ProgressBarStyle.ASCII) if you want ASCII output style
pb.start(); // the progress bar starts timing
// Or you could combine these two lines like this:
//   ProgressBar pb = new ProgressBar("Test", 100).start();
some loop {
  ...
  pb.step(); // step by 1
  pb.stepBy(n); // step by n
  ...
  pb.stepTo(n); // step directly to n
  ...
  pb.maxHint(n);
  // reset the max of this progress bar as n. This may be useful when the program
  // gets new information about the current progress.
  // Can set n to be less than zero: this means that this progress bar would become
  // indefinite: the max would be unknown.
  ...
  pb.setExtraMessage("Reading..."); // Set extra message to display at the end of the bar
}
pb.stop() // stops the progress bar

Solution 3 - Java

I found the following code to work correctly. It writes bytes to the output buffer. Perhaps that methods using a writer like the System.out.println() method replaces the occurrences of \r to \n to match the target's native line ending(if not configured properly).

public class Main{
    public static void main(String[] arg) throws Exception {
        String anim= "|/-\\";
        for (int x =0 ; x < 100 ; x++) {
            String data = "\r" + anim.charAt(x % anim.length()) + " " + x;
            System.out.write(data.getBytes());
            Thread.sleep(100);
        }
    }
}

Solution 4 - Java

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");
    }
}

Solution 5 - Java

C# Example but I'm assuming this is the same for System.out.print in Java. Feel free to correct me if I'm wrong.

Basically, you want to write out the \r escape character to the start of your message which will cause the cursor to return to the start of the line (Line Feed) without moving to the next line.

    static string DisplayBar(int i)
    {
        StringBuilder sb = new StringBuilder();

        int x = i / 2;
        sb.Append("|");
        for (int k = 0; k < 50; k++)
            sb.AppendFormat("{0}", ((x <= k) ? " " : "="));
        sb.Append("|");

        return sb.ToString();
    }

    static void Main(string[] args)
    {
        for (int i = 0; i <= 100; i++)
        {
            System.Threading.Thread.Sleep(200);
            Console.Write("\r{0} {1}% Done", DisplayBar(i), i);
        }

        Console.ReadLine();

    }

Solution 6 - Java

A bit refactored and updated @maytham-ɯɐɥʇʎɐɯ 's method. Now it's supporting an arbitrary size of the progress bar:

    public static void progressPercentage(int done, int total) {
        int size = 5;
        String iconLeftBoundary = "[";
        String iconDone = "=";
        String iconRemain = ".";
        String iconRightBoundary = "]";

        if (done > total) {
            throw new IllegalArgumentException();
        }
        int donePercents = (100 * done) / total;
        int doneLength = size * donePercents / 100;

        StringBuilder bar = new StringBuilder(iconLeftBoundary);
        for (int i = 0; i < size; i++) {
            if (i < doneLength) {
                bar.append(iconDone);
            } else {
                bar.append(iconRemain);
            }
        }
        bar.append(iconRightBoundary);

        System.out.print("\r" + bar + " " + donePercents + "%");

        if (done == total) {
            System.out.print("\n");
        }
    }

Solution 7 - Java

Here is a modified version of the above:

private static boolean loading = true;
private static synchronized void loading(String msg) throws IOException, InterruptedException {
	System.out.println(msg);
	Thread th = new Thread() {
		@Override
		public void run() {
			try {
				System.out.write("\r|".getBytes());
				while(loading) {
					System.out.write("-".getBytes());
					Thread.sleep(500);
				}
				System.out.write("| Done \r\n".getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	};
	th.start();
}

... and in main:

loading("Calculating ...");

Solution 8 - Java

I edited Eoin Campbell's code to java and added formatted progress in percents.

public static String progressBar(int currentValue, int maxValue) {
    int progressBarLength = 33; //
    if (progressBarLength < 9 || progressBarLength % 2 == 0) {
        throw new ArithmeticException("formattedPercent.length() = 9! + even number of chars (one for each side)");
    }
    int currentProgressBarIndex = (int) Math.ceil(((double) progressBarLength / maxValue) * currentValue);
    String formattedPercent = String.format(" %5.1f %% ", (100 * currentProgressBarIndex) / (double) progressBarLength);
    int percentStartIndex = ((progressBarLength - formattedPercent.length()) / 2);

    StringBuilder sb = new StringBuilder();
    sb.append("[");
    for (int progressBarIndex = 0; progressBarIndex < progressBarLength; progressBarIndex++) {
        if (progressBarIndex <= percentStartIndex - 1
        ||  progressBarIndex >= percentStartIndex + formattedPercent.length()) {
            sb.append(currentProgressBarIndex <= progressBarIndex ? " " : "=");
        } else if (progressBarIndex == percentStartIndex) {
            sb.append(formattedPercent);
        }
    }
    sb.append("]");
    return sb.toString();
}

int max = 22;
System.out.println("Generating report...");
for (int i = 0; i <= max; i++) {
   Thread.sleep(100);
   System.out.print(String.format("\r%s", progressBar(i, max)));
}
System.out.println("\nSuccessfully saved 32128 bytes");

And output:

Generating report...

[========      24.2 %             ]

[============  45.5 %             ]

[============  78.8 % =====       ]

[============  87.9 % ========    ]

[============ 100.0 % ============]

Successfully saved 32128 bytes

Solution 9 - Java

This would be possible with a Java Curses library. This is what I have found. I haven't used it myself and I don't know if it is cross-platform.

Solution 10 - Java

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");
}

Solution 11 - Java

I have recently faced the same problem, you can check my code: I have set it for one # on 5%, which you can modify later.

public static void main (String[] args) throws java.lang.Exception
{
	int i = 0;
	while(i < 21) {
		System.out.print("[");
		for (int j=0;j<i;j++) {
			System.out.print("#");
		}

		for (int j=0;j<20-i;j++) {
			System.out.print(" ");
		}

		System.out.print("] "+  i*5 + "%");
		if(i<20) {
			System.out.print("\r");
			Thread.sleep(300);
		}
		i++;
	}
	System.out.println();
}

Solution 12 - Java

static String progressBar(int progressBarSize, long currentPosition, long startPositoin, long finishPosition) {
	String bar = "";
	int nPositions = progressBarSize;
	char pb = '░';
	char stat = '█';
	for (int p = 0; p < nPositions; p++) {
		bar += pb;
	}
	int ststus = (int) (100 * (currentPosition - startPositoin) / (finishPosition - startPositoin));
	int move = (nPositions * ststus) / 100;
	return "[" + bar.substring(0, move).replace(pb, stat) + ststus + "%" + bar.substring(move, bar.length()) + "]";
}

image

Solution 13 - Java

public static void main(String[] argv) throws Exception{
       
	
	System.out.write("\r".getBytes());
	int percentage =10;
    while(percentage <= 100) {
        String temp =generateStars(percentage);
    	System.out.write(temp.getBytes());
    	System.out.print("\b\b\b");
    	percentage = percentage+10;
        Thread.sleep(500);
    }
}
	
	public static String generateStars(int percentage)
	{
		int startsNum = percentage / 4;
		StringBuilder builder = new StringBuilder();
		while(startsNum >= 0)
		{
		builder.append("*");
		startsNum--;
		}
		builder.append(percentage+"%");
		return builder.toString();
	}

Solution 14 - Java

It doesn't need to be complicated.

enter image description here

public class Demo {
  private static final StringBuilder sb = new StringBuilder();

  public static void main (String[] args) throws java.lang.Exception
  {
    for (int i = 0 ; i <= 100 ; i++) {
      sb.setLength(0);
      for (int j = 0 ; j < i; j++) {
        sb.append("#");
      }
      Thread.sleep(100);
      System.out.print("[" + String.format("%-100s", sb.toString()) + "] " +  i + "%");
      System.out.print("\r");
    }
  }
}

Solution 15 - Java

public class ProgressBar
{
	private int max;
	
	public ProgressBar(int max0) {
		max = max0;
		update(0);
	}
	
	public void update(int perc) {
		String toPrint = "|";
		for(int i = 0; i < max; i++) {
			if(i <= (perc + 1))
				toPrint += "=";
			else
				toPrint += " ";
		}
		
		if(perc >= max)
			Console.print("\r");
		else
			Console.print(toPrint + "|\r");
	}
}

Solution 16 - Java

public class Main {

    public static void main(String[] args) throws Exception {

        System.out.println("Loading : ");
            int count =1;
            for(int j=1;j<150;j++){

                System.out.print("\r");
                if(count==1){
                    System.out.print("/");
                    count++;
                }
                else if(count==2){
                    System.out.print("|");
                    count++;
                }
                else if(count==3){
                    System.out.print("-");
                    count++;
                }
                else if(count==4){
                    System.out.print("\\");
                    count++;
                }
                else if(count==5){
                    System.out.print("|");
                    count++;
                }
                else
                    count = 1;
            Thread.sleep(200);
        }

        }

    }

Solution 17 - Java

public class ConsoleApp {
    static String DisplayBar(int i)
    {
        StringBuilder sb = new StringBuilder();

        int x = i / 2;
        sb.append("|");
        for (int k = 0; k < 50; k++)
            sb.append(String.format("%s", ((x <= k) ? " " : "=")));
        sb.append("|");

        return sb.toString();
    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i <= 100; i++)
        {
            Thread.sleep(200);
            System.out.printf("\r%s %s  Done", DisplayBar(i), i);
        }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiong andrieuView Question on Stackoverflow
Solution 1 - JavaMatthias WandelView Answer on Stackoverflow
Solution 2 - JavakopporView Answer on Stackoverflow
Solution 3 - JavakeesjView Answer on Stackoverflow
Solution 4 - JavaMaytham FahmiView Answer on Stackoverflow
Solution 5 - JavaEoin CampbellView Answer on Stackoverflow
Solution 6 - JavaDenisView Answer on Stackoverflow
Solution 7 - Javauser3563245View Answer on Stackoverflow
Solution 8 - JavaMarko ŠtumbergerView Answer on Stackoverflow
Solution 9 - JavakgiannakakisView Answer on Stackoverflow
Solution 10 - JavamkeathleyView Answer on Stackoverflow
Solution 11 - JavaAashutosh RathiView Answer on Stackoverflow
Solution 12 - JavaNikolayView Answer on Stackoverflow
Solution 13 - Javavootla561View Answer on Stackoverflow
Solution 14 - JavaJin LimView Answer on Stackoverflow
Solution 15 - JavalarsaarsView Answer on Stackoverflow
Solution 16 - JavaArun JosephView Answer on Stackoverflow
Solution 17 - JavaSalem loressView Answer on Stackoverflow