将给定的字节数转换为人类可读的字符串格式。
/** * * jerry - Common Java Functionality * Copyright (c) 2012-2015, Sandeep Gupta * * http://sangupta.com/projects/jerry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.util.Arrays; //时 代 J a v a 公 众 号 - nowjava.com 提 供 public class Main{ public static void main(String[] argv) throws Exception{ long bytes = 2; System.out.println(getReadableByteCount(bytes)); } /** * Convert the given number of bytes to human-readable {@link String} format. * * @param bytes * @return */ public static String getReadableByteCount(long bytes) { if (bytes < FileUtils.ONE_KB) { return bytes + " B"; } int exp = (int) (Math.log(bytes) / Math.log(FileUtils.ONE_KB)); String pre = "" + "KMGTPE".charAt(exp - 1); double value = bytes / Math.pow(FileUtils.ONE_KB, exp);