我想使用此代码将字节转换为正确的值
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String readableFileSize = readableFileSize(9394343298L);
System.out.println("Result " + readableFileSize);
}
public static String readableFileSize(long size)
{
if (size <= 0)
return "0";
final String[] units = new String[]
{
"B", "kB", "MB", "GB", "TB"
};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
}
矿脉可以工作,但我必须在数字后面加上 L。就我而言,我使用闭源库,当我使用它时,我无法添加 L。有没有办法重构代码以将非常大的值转换为正确的格式?
最佳答案
我想你指的是这里的“L”?
String readableFileSize = readableFileSize(9394343298L);
这就是在 Java 中构造 long
类型而不是 int
类型常量的方法。
来自Primitive Data Types - Integer Literals :
An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int. It is recommended that you use the upper case letter L because the lower case letter l is hard to distinguish from the digit 1.
如果您正在使用一个库,它似乎已经为您提供了一个long
,或者可以转换为一个的东西。例如,您可以将 int
“向上转换”为 long
,但不能安全地采用相反的方式。
另请参阅:Initialize a long in Java
<小时/>我希望您的代码如何与库一起使用的示例:
public static void main(String[] args) throws Exception {
LibraryObject lib = new LibraryObject();
long someSize = lib.doSomething();
String readableFileSize = readableFileSize(someSize);
}
但是,如果没有更多关于您正在使用的这个“库”的用途、您想用它做什么等的详细信息,我无法确定。
关于java - 重构代码以获得大值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29707139/