有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中基于控制台的进展

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


共 (6) 个答案

  1. # 1 楼答案

    我使用以下代码:

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

    结果是: enter image description here

  2. # 2 楼答案

    我很确定没有办法更改控制台已经打印的任何内容,因为Java认为控制台(standard out)是一个打印流

  3. # 3 楼答案

    可以打印回车\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) {}
      }
    }
    
  4. # 6 楼答案

    我不认为有一种内在的能力来做你想要的事情

    有一个图书馆可以做到这一点(JLine)

    看到这个tutorial