Command line progress bar in Java

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

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

提交回复
热议问题