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

时间:2015-02-04 08:04:57

标签: java file download

我想在应用程序中检查我的downloadspeed,为此我将从服务器下载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 ");
    }
}

5 个答案:

答案 0 :(得分:1)

使用DecimalFormat

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator(',');
df.setDecimalFormatSymbols(symbols);
     log.logToLogger("lade " + dataRead + " Bytes -> " + ´df.format(tempPercentage) + "% geladen"); 

答案 1 :(得分:1)

您需要将222331664字面值设为float

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

要格式化,请使用:

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

答案 2 :(得分:0)

您可以使用String.format,例如:

String.format("%.2f", tempPercentage);

答案 3 :(得分:0)

如果我理解正确,你想在逗号后将你的浮点数舍入到1位小数?如果是这种情况,请尝试:

float tempPercentage = (totalDownload * 100) / 222331664;
String roundedPercentage = String.format("%.1f, tempPercentage);
log.logToLogger("lade " + dataRead + " Bytes -> " + roundedPercentage + "% geladen");

1中的%.1f是逗号后您想要的小数位数,因此如果您稍后决定在逗号后面想要2位小数,则只需更改此%.2f

答案 4 :(得分:0)

如果您需要更灵活的格式,可以使用DecimalFormat