gpt4 book ai didi

java - 使用java在控制台绘制进度条

转载 作者:行者123 更新时间:2023-12-02 13:00:33 25 4
gpt4 key购买 nike

从命令行安装某些软件包时,有时您可以看到控制台中显示进度条。并且根据进度在同一行更新。

更新时如何清屏?

最佳答案

I'm using Mac with Java 8. This demo works for me. I didn't test it on Windows :(

NOTE: if you run the code in your IDE(eg. IntelliJ, Eclipse, etc.), it may doesn't work. The right place to test it is in the terminal.

运行步骤

  1. 打开终端中此代码所在的文件夹;
  2. 编译代码javac Demo.java
  3. 运行它java演示

    import java.io.IOException;
    import java.util.concurrent.TimeUnit;

    public class Demo {
    public static void main(String[] args) throws InterruptedException, IOException {

    int i = 0;
    int j;

    while (i <= 100) {
    System.out.print("\033[H\033[2J");
    j = 0;
    for (j = 0; j < i; j++) {
    System.out.print('■');
    }
    for (; j <= 100; j++) System.out.print(' ');
    System.out.print(i + "%");
    TimeUnit.SECONDS.sleep(1);
    i += 2;
    }
    }
    }

附注。

在上面的代码中,您可能会对这一行感到困惑:System.out.print("\033[H\033[2J");

  • “H”表示移动到屏幕顶部
  • “2J”表示“清除整个屏幕”

这里是详细的explanation

关于java - 使用java在控制台绘制进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44321817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com