Android File Size Readable Format getSizeInKbytes(final File path)

Here you can find the source of getSizeInKbytes(final File path)

Description

Gets the size of the path in kbytes.

License

Open Source License

Parameter

Parameter Description
path path

Return

size in megabytes

Declaration

public static double getSizeInKbytes(final File path) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.File;

public class Main {
    private static final double ONE_KB_BYTES = 1024.0;

    /**//  w w  w  .  j av  a  2 s . c  om
     * Gets the size of the path in kbytes.
     * <p>
     * If the path is a directory the size is the sum of the size of all the files in the
     * directory and sub-directories. If the path is a file, the size is the size of the
     * file.
     * </p>
     * 
     * @param path path
     * @return size in megabytes
     */
    public static double getSizeInKbytes(final File path) {
        return getSize(path) / ONE_KB_BYTES;
    }

    /**
     * Gets the size of the path.
     * <p>
     * If the path is a directory the size is the sum of the size of all the files in the
     * directory and sub-directories. If the path is a file, the size is the size of the
     * file.
     * </p>
     * 
     * @param path path
     * @return path size in bytes
     */
    public static long getSize(final File path) {
        long size = 0;
        if (path.isFile()) {
            size = path.length();
        } else {
            File[] subFiles = path.listFiles();

            for (File file : subFiles) {
                if (file.isFile()) {
                    size += file.length();
                } else {
                    size += getSize(file);
                }
            }
        }

        return size;
    }
}

Related

  1. getSizeInMegabytes(final File path)
  2. formatFileSize(long fileLength)
  3. fileSizeFormat(long length)
  4. fileSizeFormat(long length, int lev)