Java File Size Readable Format formatFileSize(long bytes, boolean si)

Here you can find the source of formatFileSize(long bytes, boolean si)

Description

format File Size

License

Open Source License

Declaration

public static String formatFileSize(long bytes, boolean si) 

Method Source Code

//package com.java2s;
/*/*from  ww  w .j a  va2s .  com*/
 * Copyright (c) 2016. Sten Martinez
 *
 * 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 2 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, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

public class Main {
    public static String formatFileSize(long bytes, boolean si) {
        // thanks stackoverflow
        int unit = si ? 1000 : 1024;
        if (bytes < unit)
            return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }
}

Related

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