2011-01-01 1 views
23

명령 줄 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