Tom*_*nal 38 java console console-application
我想在命令行Java程序中添加进度指示器.
例如,如果我使用的是wget,它会显示:
71% [===========================> ] 358,756,352 51.2M/s eta 3s
Run Code Online (Sandbox Code Playgroud)
是否可以在没有向底部添加新行的情况下更新进度指示器?
谢谢.
Mik*_*neu 49
我使用以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
rfe*_*eak 41
首先,当你写,不要使用writeln().使用write().其次,您可以使用"\ r"来回车而不使用\n这是一个新行.回车应该让你回到线的开头.
| 归档时间: |
|
| 查看次数: |
29247 次 |
| 最近记录: |