在Java控制台基于进程[复制](Console based progress in Java [d

2019-06-23 09:28发布

这个问题已经在这里有一个答案:

  • 在Java命令行的进度条 13回答

是否有实现在Java进程滚动百分比,显示在控制台中简单的方法? 我有在特定过程中,我产生一个百分比数据类型(双),但我可以强制控制台窗口,并刷新它,而不是只打印每个新的更新,以百分比新行? 我在想推CLS和更新,因为我在Windows环境中工作,但我希望的Java有某种的内置功能。 所有建议欢迎! 谢谢!

Answer 1:

您可以打印一个回车\r把光标回行的开头。

例:

public class ProgressDemo {
  static void updateProgress(double progressPercentage) {
    final int width = 50; // progress bar width in chars

    System.out.print("\r[");
    int i = 0;
    for (; i <= (int)(progressPercentage*width); i++) {
      System.out.print(".");
    }
    for (; i < width; i++) {
      System.out.print(" ");
    }
    System.out.print("]");
  }

  public static void main(String[] args) {
    try {
      for (double progressPercentage = 0.0; progressPercentage < 1.0; progressPercentage += 0.01) {
        updateProgress(progressPercentage);
        Thread.sleep(20);
      }
    } catch (InterruptedException e) {}
  }
}


Answer 2:

我用下面的代码:

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(current == 0 ? (int) (Math.log10(total)) : (int) (Math.log10(total)) - (int) (Math.log10(current)), " ")))
        .append(String.format(" %d/%d, ETA: %s", current, total, etaHms));

    System.out.print(string);
}

结果:



Answer 3:

我在Java编写这样的包。

https://github.com/ctongfei/progressbar



Answer 4:

我不认为有一个内置的能力,你在找什么。

有一个库,将做到这一点(的JLine)。

请参见本教程



Answer 5:

我肯定是没有办法改变这种状况控制台已经印制因为Java认为控制台(标准输出)是一个PrintStream什么。



Answer 6:

不知道建在Java本身什么,但你可以使用终端控制代码做的事情一样重新定位光标。 这里的一些细节: http://www.termsys.demon.co.uk/vtansi.htm



Answer 7:

通过运行OS特定命令清除控制台,然后打印新的百分比



Answer 8:

import java.util.Random;

public class ConsoleProgress {

    private static String CURSOR_STRING = "0%.......10%.......20%.......30%.......40%.......50%.......60%.......70%.......80%.......90%.....100%";

    private static final double MAX_STEP = CURSOR_STRING.length() - 1;

    private double max;
    private double step;
    private double cursor;
    private double lastCursor;

    public static void main(String[] args) throws InterruptedException {
        // ---------------------------------------------------------------------------------
        int max = new Random().nextInt(400) + 1;
        // ---------------------------------------------------------------------------------
        // Example of use :
        // ---------------------------------------------------------------------------------
        ConsoleProgress progress = new ConsoleProgress("Progress (" + max + ") : ", max);
        for (int i = 1; i <= max; i++, progress.nextProgress()) {
            Thread.sleep(3L); // a task with no prints
        }
    }

    public ConsoleProgress(String title, int maxCounts) {
        cursor = 0.;
        max = maxCounts;
        step = MAX_STEP / max;
        System.out.print(title);
        printCursor();
        nextProgress();
    }

    public void nextProgress() {
        printCursor();
        cursor += step;
    }

    private void printCursor() {
        int intCursor = (int) Math.round(cursor) + 1;
        System.out.print(CURSOR_STRING.substring((int) lastCursor, intCursor));
        if (lastCursor != intCursor && intCursor == CURSOR_STRING.length())
            System.out.println(); // final print
        lastCursor = intCursor;
    }
}


Answer 9:

迟到的聚会,但这里有一个答案:

public static String getSingleLineProgress(double progress) {
    String progressOutput = "Progress: |";
    String padding = Strings.padEnd("", (int) Math.ceil(progress / 5), '=');
    progressOutput += Strings.padEnd(padding, 0, ' ') + df.format(progress) + "%|\r";
    if (progress == 100.0D) {
        progressOutput += "\n";
    }
    return progressOutput;
}

请记住,使用System.out.print()代替System.out.println()



文章来源: Console based progress in Java [duplicate]