Java File Size Readable Format formatDataSize(long size)

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

Description

Formats the data size in B, KB, MB or GB, TB as needed

License

Open Source License

Declaration

public static String formatDataSize(long size) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w  . ja v a  2 s.c  om*/
       
This file is part of the Xapagy Cognitive Architecture 
Copyright (C) 2008-2017 Ladislau Boloni
    
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
    
You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
       
*/

public class Main {
    /**
     * Formats the data size in B, KB, MB or GB, TB as needed
     * 
     * @return
     */
    public static String formatDataSize(long size) {
        double dsize = size;
        String retval = "";
        if (dsize < 1024.0) {
            retval = size + " B";
            return retval;
        }
        if (dsize < 1024.0 * 1024.0) {
            double val = Math.round(dsize / 1024.0 * 10.0) / 10.0;
            retval = val + " KB";
            return retval;
        }
        if (dsize < 1024.0 * 1024.0 * 1024.0) {
            double val = Math.round(dsize / (1024.0 * 1024.0) * 10.0) / 10.0;
            retval = val + " MB";
            return retval;
        }
        if (dsize < 1024.0 * 1024.0 * 1024.0 * 1024.0) {
            double val = Math.round(dsize / (1024.0 * 1024.0 * 1024.0) * 10.0) / 10.0;
            retval = val + " GB";
            return retval;
        }
        double val = Math.round(dsize / (1024.0 * 1024.0 * 1024.0 * 1024.0) * 10.0) / 10.0;
        retval = val + " TB";
        return retval;
    }
}

Related

  1. formatarNumeroComZerosAEsquerda(long numero, int size)
  2. formatByteSize(long bytes, int decimals)
  3. formatByteSize(long bytes, int lastDigits)
  4. formatByteSize(long byteSize)
  5. formatByteSizeToString(long bytes)
  6. FormatDataSize(long uBytes)
  7. FormatDataSizeKB(long uBytes)
  8. formatFileSize(long bytes)
  9. formatFileSize(long bytes, boolean si)