gpt4 book ai didi

java - 用逗号显示下载文件的百分比

转载 作者:行者123 更新时间:2023-12-02 05:00:35 25 4
gpt4 key购买 nike

我想检查应用程序中的下载速度,为此我将从服务器下载 1GB zip 文件。我不知道如何用逗号得到像 12,4% 或 45,8% 这样的数字。确切的文件大小是 222331664 字节

import java.net.*;
import java.io.*;

public class SpeedTest
{
private static Logger log;
private static URL fileToDownload;

public static void main(String argc[]) throws Exception {
log = new Logger("SpeedTest");

// http://kernel.ubuntu.com/~kernel-ppa/mainline/v2.6.15/linux-headers-2.6.15-020615_2.6.15-020615_all.deb
fileToDownload = new URL("http://www.specialservice.ml/1GB.zip");

log.logToLogger("Lade " + fileToDownload);

long totalDownload = 0; // total bytes downloaded
final int BUFFER_SIZE = 1024; // size of the buffer
byte[] data = new byte[BUFFER_SIZE]; // buffer
BufferedInputStream in = new BufferedInputStream(fileToDownload.openStream());
int dataRead = 0; // data read in each try
long startTime = System.nanoTime(); // starting time of download

while ((dataRead = in.read(data, 0, 1024)) > 0) {
totalDownload += dataRead; // adding data downloaded to total data
float tempPercentage = (totalDownload * 100) / 222331664;
log.logToLogger("lade " + dataRead + " Bytes -> " + String.format("%.2f", tempPercentage) + "% geladen");
}

/* download rate in bytes per second */
float bytesPerSec = totalDownload / ((System.nanoTime() - startTime) / 1000000000);
log.logToLogger(bytesPerSec + " Bps");

/* download rate in kilobytes per second */
float kbPerSec = bytesPerSec / (1024);
log.logToLogger(kbPerSec + " KBps ");

/* download rate in megabytes per second */
float mbPerSec = kbPerSec / (1024);
log.logToLogger(mbPerSec + " MBps ");
}
}

最佳答案

您需要将 222331664 文字设置为 float

float tempPercentage = (totalDownload * 100) / 222331664f;

要格式化它,请使用:

String.format("%.1f", tempPercentage).replace(".", ",");

关于java - 用逗号显示下载文件的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28316356/

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