Java File Size Get getFolderSize(File folder)

Here you can find the source of getFolderSize(File folder)

Description

get Folder Size

License

Open Source License

Parameter

Parameter Description
folder a parameter

Return

the size of files in the folder, don't include the size of sub-folders

Declaration

public static String getFolderSize(File folder) 

Method Source Code


//package com.java2s;

import java.io.File;

import java.text.NumberFormat;

public class Main {
    public static final String[] FILE_SIZE_UNIT = { "Byte", "KB", "MB", "GB", "TB", "PB" };

    /**/*from ww w. j ava 2s .  c  o  m*/
     * 
     * @param folder
     * @return the size of files in the folder, don't include the size of sub-folders
     */
    public static String getFolderSize(File folder) {
        if (folder == null)
            return "";

        if (folder.isDirectory()) {
            return getFilesSize(folder.listFiles());
        } else {
            return "";
        }
    }

    /**
     * 
     * @param files
     *            File Array
     * @return the size of files in the file array
     */
    public static String getFilesSize(Object[] files) {
        if (files == null)
            return "";
        double filesSize = 0;
        for (Object file : files) {
            if (((File) file).isFile()) {
                filesSize += ((File) file).length();
            }
        }
        return getFormatSize(filesSize);
    }

    /**
     * 
     * @param size
     * @return the formatted size
     */
    private static String getFormatSize(double size) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        int i = 0;
        String[] unit = FILE_SIZE_UNIT;
        for (i = 0; i < unit.length; i++) {
            if ((long) (size / 1024) > 0) {
                size /= 1024;
            } else {
                break;
            }
        }
        return nf.format(size) + unit[i];
    }
}

Related

  1. getFileSizeRecursive(File file, boolean subFolders)
  2. getFileSizes(File f)
  3. getFileSizeString(File file, boolean si)
  4. getFilesizeString(long size)
  5. getFileSizeStringFor(File file)
  6. getSize(long fileSize)
  7. getSizeErrorMessage(String pattern, Long maxFileSize, Long fileSize, String fileName)
  8. getStringSizeLengthFile(long size)
  9. humanFileSize(Long longFileSize)