如何在Java中将字节大小转换为人类可读的格式?像1024应该变成"1 Kb"而1024*1024应该变成"1 Mb".
我有点厌倦为每个项目编写这个实用工具方法.Apache Commons中是否有任何静态方法?
只是想知道.NET是否提供了一种干净的方法来执行此操作:
int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
y = string.Format("{0:n1} KB", x / 1024f);
}
Run Code Online (Sandbox Code Playgroud)
等等...
有没有简单的方法来创建一个使用的类 IFormatProvider它写出一个用户友好的文件大小?
public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
Run Code Online (Sandbox Code Playgroud)
它应该导致字符串格式化为" 2,5 MB "," 3,9 GB "," 670字节 "等等.
我想知道.NET中是否有一个函数将数字字节转换为正确测量的字符串?
或者我们只需要遵循分割和保持转换单元的旧方法来完成它?