Java:在命令行中更新文本而无需换行

标签 java console console-application

我想在命令行 Java 程序中添加进度指示器。

例如,如果我使用 wget,它会显示:

71% [===========================>           ] 358,756,352 51.2M/s  eta 3s

是否有可能在不添加新行的情况下更新进度指示器?

谢谢。

最佳答案

我使用以下代码:

public static void main(String[] args) {
    long total = 235;
    long startTime = System.currentTimeMillis();

    for (int i = 1; i <= total; i = i + 3) {
        try {
            Thread.sleep(50);
            printProgress(startTime, total, i);
        } catch (InterruptedException e) {
        }
    }
}


private static void printProgress(long startTime, long total, long current) {
    long eta = current == 0 ? 0 : 
        (total - current) * (System.currentTimeMillis() - startTime) / current;

    String etaHms = current == 0 ? "N/A" : 
            String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(eta),
                    TimeUnit.MILLISECONDS.toMinutes(eta) % TimeUnit.HOURS.toMinutes(1),
                    TimeUnit.MILLISECONDS.toSeconds(eta) % TimeUnit.MINUTES.toSeconds(1));

    StringBuilder string = new StringBuilder(140);   
    int percent = (int) (current * 100 / total);
    string
        .append('\r')
        .append(String.join("", Collections.nCopies(percent == 0 ? 2 : 2 - (int) (Math.log10(percent)), " ")))
        .append(String.format(" %d%% [", percent))
        .append(String.join("", Collections.nCopies(percent, "=")))
        .append('>')
        .append(String.join("", Collections.nCopies(100 - percent, " ")))
        .append(']')
        .append(String.join("", Collections.nCopies((int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
        .append(String.format(" %d/%d, ETA: %s", current, total, etaHms));

    System.out.print(string);
}

结果: enter image description here

关于Java:在命令行中更新文本而无需换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4573123/

相关文章:

java - 如何找到Spring Data JPA和Spring版本的正确jar文件

java - 设置UI内容仅添加最后一行

c# - 如何将数据库文件导入到使用 Entity Framework 的 C# 控制台应用程序的解决方案中

java - 分发可执行 Jar 控制台应用程序

c# - 在控制台应用程序中托管的 WCF 服务

c# - C# 中的斐波那契数列

java - 发送大文件(~ 1GB)失败并出现 SocketException

java - 如何告诉客户端新的 Redis master 在哪里使用 Sentinel

c++ - 如何在C++程序中设置自定义断点?

c# - 如何修改控制台文本的前一行?