gpt4 book ai didi

java - 如何在java控制台(没有UI)中显示下载文件的百分比进度?

转载 作者:行者123 更新时间:2023-11-30 04:26:05 24 4
gpt4 key购买 nike

我的java代码部分如下。

while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}

// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1){
System.out.println("File was downloaded");
break;
}

// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;

}

/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;

}

我想通过更新控制台中的进度行来以百分比形式显示下载文件的进度。请帮忙。谢谢。

最佳答案

这是一个简单的“进度条”概念。

基本上,它使用 \b 字符在打印出新进度条之前在先前打印到控制台的字符上退格...

public class TextProgress {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("");
printProgress(0);
try {
for (int index = 0; index < 101; index++) {
printProgress(index);
Thread.sleep(125);
}
} catch (InterruptedException ex) {
Logger.getLogger(TextProgress.class.getName()).log(Level.SEVERE, null, ex);
}
}

public static void printProgress(int index) {

int dotCount = (int) (index / 10f);
StringBuilder sb = new StringBuilder("[");
for (int count = 0; count < dotCount; count++) {
sb.append(".");
}
for (int count = dotCount; count < 10; count++) {
sb.append(" ");
}
sb.append("]");
for (int count = 0; count < sb.length(); count++) {
System.out.print("\b");
}
System.out.print(sb.toString());

}
}

它无法在大多数 IDE 中运行,因为 Java 的文本组件不支持 \b 字符,您必须从终端/控制台运行

关于java - 如何在java控制台(没有UI)中显示下载文件的百分比进度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15843202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com