提问者:小点点

以用户友好的格式转换字节


我从这个例子中找到了这段代码:

private static final String[] Q = new String[]{"", "K", "M", "G", "T", "P", "E"};

public String getAsString(long bytes)
{
    for (int i = 6; i > 0; i--)
    {
        double step = Math.pow(1024, i);
        if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]);
    }
    return Long.toString(bytes);
}

我实现了这段代码,但结果看起来很可疑。我试图从JVM获取可用内存量,但我只有80 MB。您能否确认此代码是否正确地将字节转换为兆字节或千兆字节。


共1个答案

匿名用户

您的代码看起来是正确的。在运行应用程序时,尝试更改-Xmx-XmsJVM值,并查看差异。

例如,尝试运行以下内容:

JAVA_OPTS="-Xmx2G-Xms2G"javayour.Class