Console based progress in Java [duplicate]

2019-01-16 08:28发布

This question already has an answer here:

Is there are easy way to implement a rolling percentage for a process in Java, to be displayed in the console? I have a percentage data type (double) I generated during a particular process, but can I force it to the console window and have it refresh, instead of just printing a new line for each new update to the percentage? I was thinking about pushing a cls and updating, because I'm working in a Windows environment, but I was hoping Java had some sort of built-in capability. All suggestions welcomed! Thanks!

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-16 08:46

Clear the console by running the os specific command and then print the new percentage

查看更多
Emotional °昔
3楼-- · 2019-01-16 08:48

I'm quite sure there is no way to change anything that the console has already printed because Java considers the console (standard out) to be a PrintStream.

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-16 08:53

You can print a carriage return \r to put the cursor back to the beginning of line.

Example:

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) {}
  }
}
查看更多
Melony?
5楼-- · 2019-01-16 08:57

Don't know about anything built in to java itself, but you can use terminal control codes to do things like reposition the cursor. Some details here: http://www.termsys.demon.co.uk/vtansi.htm

查看更多
▲ chillily
6楼-- · 2019-01-16 08:58

I use following code:

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

The result: enter image description here

查看更多
姐就是有狂的资本
7楼-- · 2019-01-16 09:00

Late for the party, but here's an answer:

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

Remember to use System.out.print() instead of System.out.println()

查看更多
登录 后发表回答