web-dev-qa-db-ja.com

Java

コンソールで表示されるように、Javaのプロセスのローリングパーセンテージを実装する簡単な方法はありますか?特定のプロセス中に生成したパーセンテージデータタイプ(double)を持っていますが、新しい更新ごとに新しい行をパーセンテージに出力するだけでなく、強制的にコンソールウィンドウに表示して更新できますか? Windows環境で作業しているので、clsをプッシュして更新することを考えていましたが、Javaに何らかの機能が組み込まれていることを望んでいました。すべての提案を歓迎します!ありがとう!

35
Monster

キャリッジリターンを印刷できます\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) {}
  }
}
53
laalto

私は次のコードを使用します:

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

11
Mike Shauneu

そのようなパッケージをJavaで作成しました。

https://github.com/ctongfei/progressbar

7
Tongfei Chen

私はあなたが探しているものを実行するための組み込み機能はないと思います。

それを行うライブラリ(JLine)があります。

これを見てください チュートリアル

6
Glen

Javaはコンソール(標準出力)をPrintStreamと見なすので、コンソールがすでに印刷したものを変更する方法はないと確信しています。

4
David Johnstone

Java自体に組み込まれているものについては知りませんが、端末制御コードを使用してカーソルの位置を変更するなどの操作を行うことができます。詳細はこちら: http:// www。 termsys.demon.co.uk/vtansi.htm

2
Tom Jefferys

パーティーには遅れましたが、答えは次のとおりです。

_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()を使用することを忘れないでください

0
victorantunes

Os固有のコマンドを実行してコンソールをクリアし、新しいパーセンテージを出力します

0
Thejesh GN
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;
    }
}
0
Elphara77