How to get the size of a file using Java

The file Object has a method called length returning the size of the current file.

Call the following method:

	
long size = myFile.length();
		 

This example gets the size of a file using Java. It creates a file Object with using the path. Then it calls the length method to get the file size. The value is stored in a long. Finally, the size in bytes is written in the output along with the name of the file.

Create the following java file:

import java.io.File;

public class FileSize {
    public static void main(String[] argv) {

    	// Define the file Path
        final String FILE_NAME = "/tmp/FileSize.tmp";
        
        // Define the file Object
        File myFile = new File(FILE_NAME);
        
        // Get the size of the file
        long size = myFile.length();
        
        // Write the size in the output.
        System.out.println(FILE_NAME + " size = " + size + " bytes");
    }
}

The output will be:

/tmp/FileSize.tmp size = 19 bytes

The size of the file is returned in bytes. It can be converted to kilo bytes by divided the result by 1024 or it can be converted to Megabytes by dividing the number by 1024 twice.

References:

java io

Share this article:

Recent Comments