2011-01-01 10 views
23

進捗インジケータをコマンドラインJavaプログラムに追加したいとします。例えばJava:コマンドラインで改行せずにテキストを更新する

私はwgetのを使用している場合、それは示しています

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

はそれが一番下に新しい行を追加することなく、更新の進行状況インジケータを持つことは可能ですか?

ありがとうございました。

+0

@rfeak申し訳ありませんが、http://stackoverflow.com/questions/1001290/console-based-progress-in-java – TheLQ

答えて

27

最初に書き込みを行うときは、writeln()を使用しないでください。 write()を使用します。次に、改行である\ nを使用せずにキャリッジリターンに "\ r"を使用することができます。キャリッジリターンは、行の先頭に戻る必要があります。

+7

しかし、テキストの長さが縮小される可能性がある場合(たとえば、ETAを表示するのに必要な桁数が減少する場合)、古い文字にスペースを書き込んで、それ以上は表示されないようにしてください。編集:さらに、System.out.flush()を実行して、実際にテキストが実際に表示されることを確認してください(たとえば、ラインバッファーされた端末上)。 – jstanley

+0

@jstanley - 覚えておくべき点があります。 – rfeak

23

私は次のように使用するコード:

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

関連する問題