Java File Size Get getFileSizeString(File file, boolean si)

Here you can find the source of getFileSizeString(File file, boolean si)

Description

Get the formatted File size as a String <br> See http://stackoverflow.com/questions/3758606/ for more information on how to properly format the size

License

Open Source License

Parameter

Parameter Description
file a parameter
si if True, the SI Units will be used, otherwise the binary ones will be used

Return

size as a string

Declaration

public static String getFileSizeString(File file, boolean si) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2000, 2017 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from  w  w w.  j a  v  a2  s.com*/
 *     IBM Corporation - initial API and implementation
 *     Diamond Light Source - Custom modifications for Diamond's needs
 *******************************************************************************/

import java.io.File;

public class Main {
    /**
     * Get the formatted File size as a String <br>
     * See {@link http://stackoverflow.com/questions/3758606/}
     * for more information on how to properly format the size
     * 
     * @param file
     * @param si
     *         if True, the SI Units will be used, otherwise the binary ones will be used
     * @return size as a string
     */
    public static String getFileSizeString(File file, boolean si) {
        if (!file.isDirectory()) {
            long bytes = file.length();
            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);
        }
        return "";
    }
}

Related

  1. getFileSizeFormat(double inputvalue)
  2. getFileSizeFormat(String total_size)
  3. getFileSizeLabel(long sizeInBytes)
  4. getFileSizeRecursive(File file, boolean subFolders)
  5. getFileSizes(File f)
  6. getFilesizeString(long size)
  7. getFileSizeStringFor(File file)
  8. getFolderSize(File folder)
  9. getSize(long fileSize)