Java Size Format formatSize(long size)

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

Description

Formats a file size as a human-readable string.

License

Apache License

Parameter

Parameter Description
size a parameter

Return

human-readable file size

Declaration

public static String formatSize(long size) 

Method Source Code

//package com.java2s;
/*/*from w w  w .ja v a2 s  .  c om*/
 * Copyright 2012 James Moger
 *
 * 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.text.DecimalFormat;

public class Main {
    public final static long KILOBYTE = 1024L;
    public final static long MEGABYTE = 1024L * 1024L;
    public final static long GIGABYTE = 1024L * 1024L * 1024L;

    /**
     * Formats a file size as a human-readable string.
     * @param size
     * @return human-readable file size
     */
    public static String formatSize(long size) {
        if (size < 1024) {
            return size + " bytes";
        }
        double sz = size;
        String units;
        double nsz;
        String format = "0";
        if (size >= GIGABYTE) {
            nsz = sz / GIGABYTE;
            units = "GB";
            format = "0.0";
        } else if (size >= MEGABYTE) {
            nsz = sz / MEGABYTE;
            units = "MB";
            format = "0.0";
        } else {
            nsz = sz / KILOBYTE;
            units = "KB";
        }
        return new DecimalFormat(format).format(nsz) + " " + units;
    }
}

Related

  1. formatSize(long bytes)
  2. formatSize(long fileSize)
  3. formatSize(long longSize)
  4. formatSize(long longSize, int decimalPos)
  5. formatSize(long size)
  6. formatSize(long size)
  7. formatSize(long size)
  8. formatSize(long size)
  9. formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)