Pages

Wednesday 1 January 2014

GET FILE SIZE IN KB OR MB USING JAVA

This is a simple practical demo to find out size of file in KB and MB.

 GetFileSize.java

import java.io.File;
import java.text.DecimalFormat;

public class GetFileSize {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        File file = new File("D:/C++ The Complete Reference 4th Ed.pdf");
        long filesize = file.length();
        double size_in_kb = ((filesize / 1024));
        double size_in_mb = size_in_kb / 1024;
        if (size_in_kb < 1024) {
            System.out.println("File Size : " + size_in_kb + " KB");
        } else {
            System.out.println("File Size : " + Double.parseDouble(new DecimalFormat("##.##").format(size_in_mb))+" MB ");
        }
    }

}

======================================================================

No comments:

Post a Comment