Java 用逗号显示已下载文件的百分比
我想在应用程序中检查我的下载速度,为此我将从服务器下载1GB的zip文件。我想不出如何用逗号得到12,4%或45,8%这样的数字。确切的文件大小是222331664字节Java 用逗号显示已下载文件的百分比,java,file,download,Java,File,Download,我想在应用程序中检查我的下载速度,为此我将从服务器下载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(Str
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 ");
}
}
您可以使用String.format,例如:
String.format("%.2f", tempPercentage);
如果我理解正确的话,您想将浮点值四舍五入到逗号后的1位小数吗?如果是这种情况,请尝试以下方法:
float tempPercentage = (totalDownload * 100) / 222331664;
String roundedPercentage = String.format("%.1f, tempPercentage);
log.logToLogger("lade " + dataRead + " Bytes -> " + roundedPercentage + "% geladen");
%.1f
中的1
是逗号后需要的小数位数,因此,如果您以后决定在逗号后需要2个小数,只需更改此%.2f
使用:
如果需要更灵活的格式,您可以使用。您需要将
222331664
literal设置为float
float tempPercentage = (totalDownload * 100) / 222331664f;
若要格式化,请使用:
String.format("%.1f", tempPercentage).replace(".", ",");
我试过了,但总是1,00%-2,00%-3,00%,从来没有1,2%或3,4%
String.format("%.1f", tempPercentage).replace(".", ",");