Get the size of a file in java

In this instructional exercise, we will figure out how to get or compute the measure of a record in java with a basic and simple precedent. As a rule, you may need to compute the document measure for further tasks in a specific content record. Let’s learn how to get the size of a file in Java.

In the event that you don’t have a clue how to compute the document measure, at that point you are at the correct spot. Since in this instructional exercise, we going to discover how to get the document estimate.

 

Get the size of a file in java

Let’s learn this with some easy examples.

At first import a package named “File” to your java program to access the pre-defined classes to your java program.
You can do it by:

import java.io.File;
or,
import java.io.*;

Now, create a text file and write some content in it and save it.

In java program after importing File package, create a File object which will contain the path of the particular text file which you want to refer to perform the further operations as per your requirements in a file.
You can do it by:

File obj_name= new File("name_of_text_file.txt");

Now, If you want to perform any operations in a file if and only if file exists then use exists() function to check whether a file exists or not.
You can do it by:

if(obj_name.exists())

After that, use length function to determine the size of a file in bytes.
For this write:

double bytes=obj_name.length()

 

Calculate the size of a file

import java.io.File;
class FileSizeDemoExample
{
    public static void main(String []args)
    {
        File f=new File("Example.txt");
        if(f.exists())
        {
            double bytes=f.length();
            System.out.println("File size in bytes="+bytes);
        }
        else
            System.out.println("File does not exist mention existing file");
    }
}

Also read:

Leave a Reply

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