java.io.File
is my favorite utility which deals with lots of File related to functionalities. I started dealing with Java and File utils more and more in my initial coding days. It’s always fun to perform number of different operations using java.io.File
.
In Java, you can use the File.length()
method to get the file size in bytes.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.crunchify.tutorials; import java.io.File; /** * @author Crunchify.com */ public class CrunchifyFindFileFolderSize { public static void main(String[] args) { File file = new File("/Users/<username>/Documents/log.txt"); long size = 0; size = getFileFolderSize(file); double sizeMB = (double) size / 1024 / 1024; String s = " MB"; if (sizeMB < 1) { sizeMB = (double) size / 1024; s = " KB"; } System.out.println(file.getName() + " : " + sizeMB + s); } public static long getFileFolderSize(File dir) { long size = 0; if (dir.isDirectory()) { for (File file : dir.listFiles()) { if (file.isFile()) { size += file.length(); } else size += getFileFolderSize(file); } } else if (dir.isFile()) { size += dir.length(); } return size; } } |