Java File Size Sample Code

The File Class contains a method called length(), which will return the length or size of a file on the filesystem. The method will return the length in bytes or 0L if the file does not exist. You will get the same 0L if querying for the size of a directory or folder. If the calling application doe snot have read access to the file, it will throw a SecurityException.

As a Java programmer, I think in terms of the footprint my application is taking from the virtual machine, which means I like to think in Megabytes. The length() method returns a long value that represents bytes, which can be easily converted into megabytes if divided by 1024. I also display the file lengths in megabytes in the sample code.

Java Class: File
Method Name: length()
Parameters: none
Return Type: long
Exceptions: SecurityException

Java File Size Sample Code:



public class JavaFileSize {

	 public static void main( String[] args )
		long len = 0;
		long mbytes = 0;
		//String with path of filename 
		String sampleFile1 = "C:\\Users\\Admin\\Documents\\JavaFile.txt";
		String sampleFile2 = "C:\\Users\\Admin\\eclipse\\java-oxygen\\eclipse\\eclipse.exe";
			//Create File objects
			File file1 = new File(sampleFile1);
			File file2 = new File(sampleFile2);
			String fileName1 = file1.getName();
			String fileName2 = file2.getName();
			//Get length of file1
			len = file1.length();
			//Convert to megabytes
			mbytes = len / 1024;
			System.out.println("Byte Length of "+fileName1+": "+len+" Or Megabytes: "+mbytes);
			//Get length of file1
			len = file2.length();
			//Convert to megabytes
			mbytes = len / 1024;
			System.out.println("Byte Length of "+fileName2+": "+len+" Or Megabytes: "+mbytes);
		catch(Exception ex)

Java File Size Sample Output:

Byte Length of JavaFile.txt: 85 Or Megabytes: 0
Byte Length of eclipse.exe: 312832 Or Megabytes: 305


Add a Comment

Your email address will not be published. Required fields are marked *