Java - Get size of file or folder

Posted on November 2, 2016


This example shows how to get size of file and folder using the length() method of File class. The length() method return size of file in byte and 0L if file does not exist.

Here is an example of File.lenght().

FileSizeExample.java

package com.boraji.tutorial.io;

import java.io.File;

/**
 * @author imssbora
 * FileSizeExample.java
 * Nov 2, 2016
 */
public class FileSizeExample {
	public static void main(String[] args) {
		
		System.out.println("--------------File Size-----------------");
		File file=new File("D:\\HelloJava.txt");
		if(file.exists()){
			System.out.println("File size in bytes : "+file.length());
		}else{
			System.out.println("File does not exist.");
		}
		
		System.out.println("\n------------Folder Size----------------");
		File folder=new File("D:\\Work\\Java");
		long folderSize=getFolderSize(folder);
		System.out.println("Folder size in bytes : "+folderSize);
	}

	/**
	 * @param folder
	 * @return size
	 */
	private static long getFolderSize(File folder) {
		long size=0;
		for(File file:folder.listFiles()){
			if(file.isFile()){
				size+=file.length();
			}else{
				size+=getFolderSize(file);
			}
		}
		return size;
	}
}	

Output

--------------File Size-----------------
File size in bytes : 1896

------------Folder Size----------------
Folder size in bytes : 102768