generate readable File Size from long value - Java java.lang

Java examples for java.lang:long Format

Description

generate readable File Size from long value

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        long size = 42;
        System.out.println(generateFileSize(size));
    }/*from ww w  . j a v a 2  s  . c  om*/

    private static final double KB = 1024.0;
    private static final double MB = 1048576.0;
    private static final double GB = 1073741824.0;

    public static String generateFileSize(long size) {
        String fileSize;
        if (size < KB)
            fileSize = size + "B";
        else if (size < MB)
            fileSize = String.format("%.1f", size / KB) + "KB";
        else if (size < GB)
            fileSize = String.format("%.1f", size / MB) + "MB";
        else
            fileSize = String.format("%.1f", size / GB) + "GB";

        return fileSize;
    }
}

Related Tutorials