Java File Size Readable Format formatFileSize(long fileSize)

Here you can find the source of formatFileSize(long fileSize)

Description

Formats fileSize (in byte) in B/KB/MB/GB

License

Open Source License

Parameter

Parameter Description
fileSize a parameter

Declaration

public static String formatFileSize(long fileSize) 

Method Source Code

//package com.java2s;
/*//ww  w.j  ava  2 s  . co  m
 *     Orbit, a versatile image analysis software for biological image-based quantification.
 *     Copyright (C) 2009 - 2017 Idorsia Pharmaceuticals Ltd., Hegenheimermattweg 91, CH-4123 Allschwil, Switzerland.
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

public class Main {
    /**
     * Formats fileSize (in byte) in B/KB/MB/GB
     *
     * @param fileSize
     * @return
     */
    public static String formatFileSize(long fileSize) {
        String unit = "B";
        double size = 0;

        if (fileSize < 1024) {
            unit = "B";
            size = (double) fileSize;
        } else if (fileSize < (1024 * 1024L)) {
            unit = "KB";
            size = (double) fileSize / (1024L);
        } else if (fileSize < (1024 * 1024 * 1024L)) {
            unit = "MB";
            size = (double) fileSize / (1024 * 1024L);
        } else {
            unit = "GB";
            size = (double) fileSize / (1024 * 1024 * 1024L);
        }

        return String.format("%1$.2f", size) + " " + unit;
    }
}

Related

  1. formatDataSize(long size)
  2. FormatDataSize(long uBytes)
  3. FormatDataSizeKB(long uBytes)
  4. formatFileSize(long bytes)
  5. formatFileSize(long bytes, boolean si)
  6. formatFileSize(long fileSize)
  7. formatFileSize(long fileSize)
  8. formatFileSize(long fileSizeLong)
  9. formatFileSize(long size)