簡體   English   中英

將字節大小轉換為 Java 中的人類可讀格式?

[英]convert byte size into human readable format in Java?

我正在嘗試創建 static 方法String formatSize(long sizeInBytes)此方法需要將提供的文件大小(以字節為單位)的最合適的表示形式返回為至少有 2 個小數位(字節除外)的人類可讀格式。

這是我的代碼

public class HexEditor {

    public static void main(String[] args) {
        System.out.println(formatSize(2147483647));
        System.out.println(formatSize(123));
        System.out.println(formatSize(83647));
        System.out.println(formatSize(9585631));
        System.out.println(formatSize(188900977659375L));
    }
    public static String floatForm (double d){
       return new DecimalFormat("#.##").format(d);
    }

    public static String formatSize(long size) {


        double B = 1 * 8;
        double kibit = 1024;
        double KiB = B * kibit;
        double MiB = KiB * kibit;
        double GiB = MiB * kibit;
        double TiB = GiB * kibit;
        double Pib = TiB * kibit;

        if (size < kibit) {
            return size + " byte";

        } else if (size < KiB) {
            double result = size / kibit;
            return floatForm (result) + " Kibit";

        } else if (size < MiB) {
            double result = size / KiB;
            return floatForm (result) + " KiB";

        } else if (size < GiB) {
            double result = size / MiB;
            return floatForm (result) + " MiB";

        } else if (size < TiB) {
            double result = size / GiB;
            return floatForm (result) + " GiB";

        } else if (size < Pib) {
            double result = size / TiB;
            return floatForm (result) + " TiB";
        }

        return "";
    }

}

這些是我的輸入並期望輸出

輸入 Output

2147483647          2.00 GiB
123                 123 bytes
83647               81.69 KiB
9585631             9.14 MiB
188900977659375     171.80 TiB

但是當我的代碼運行時,它會給出不同的輸出

    256 MiB
    123 byte
    10.21 KiB
    1.14 MiB
    21.48 TiB

我錯了嗎? 或者其他的東西

您正在按位除,但您的輸入已經是字節,而不是位。 因此,除了 < KB 計算之外,您最終得到的結果都是預期大小計算的 1/8。

試一試以下代碼(添加打印語句只是為了檢查除數):

        double KiB = Math.pow(2, 10);
        double MiB = Math.pow(2, 20);
        double GiB = Math.pow(2, 30);
        double TiB = Math.pow(2, 40);
        double Pib = Math.pow(2, 50);

        NumberFormat df = DecimalFormat.getInstance();
        System.out.println("KiB: " + df.format(KiB));
        System.out.println("MiB: " + df.format(MiB));
        System.out.println("GiB: " + df.format(GiB));
        System.out.println("TiB: " + df.format(TiB));
        System.out.println("Pib: " + df.format(Pib));

        if (size < KiB) {
            return size + " byte";

        } else if (size < MiB) {
            double result = size / KiB;
            return floatForm(result) + " KiB";

        /* remaining code is identical to yours */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM