Java File Size Readable Format formatSize(long size)

Here you can find the source of formatSize(long size)

Description

Change byte to KB/MB/GB...(Accurate to two decimal places)

License

Apache License

Parameter

Parameter Description
context a parameter
size a parameter

Declaration

public static String formatSize(long size) 

Method Source Code

//package com.java2s;
/*//from  w ww  .j  a  va2 s .com
 * Copyright (C) 2013 The Open Source Project By Yunying.Zhang
 *
 * 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.
 * author:Yunying.Zhang
 * date:2013-09-27
 */

public class Main {
    /**
     * Change byte to KB/MB/GB...(Accurate to two decimal places)
     * @param context
     * @param size
     * @return
     */
    public static String formatSize(long size) {
        if (size <= 0) {
            return "0B";
        }
        String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "NB", "DB", "CB", };
        int i = 0;
        float newSize = size;
        while (newSize >= 1024) {
            newSize /= 1024;
            i++;
        }
        if (i > units.length - 1) {
            return "Unknown";
        }
        return String.format("%.2f", newSize) + units[i];
    }
}

Related

  1. formatShortByte(long size)
  2. formatSize(double size)
  3. formatSize(Integer size)
  4. formatSize(long bytes)
  5. formatSize(long bytes, String b, String kb, String mb, String gb)
  6. FormatSize(long size)
  7. formatSize(long size)
  8. formatSize(long size)
  9. formatSize(long size)