How to Get the Size of a File Using Java

Java


In this article, we show how to get the size of a file using object.

As you access any file, you must create a object of the File class and pass in the parameter of the file that you want to retrieve.

Once you have done this, then you just need to use the length() function to get the size of the file.

The Java length() function, when working with files, returns the size of the file in unit bytes.

The code to get the size of a file in Java is shown below.



So in the file above we create a class called Filesize.

We create our main method, which is the point in our code where execution begins.

We then create a file object. This represents the file that we want to retrieve. Inside of the parameter to the file object, we pass in the argument "file.txt". This represents the name of the name of the file that we want to retrieve. When put this argument into the File object, this calls the default constructor of the File class and passes the "file.txt" value into the File object.

Once we have this File object created, we then reference this file object by f.

So to output the size of the file in bytes, we use System.out.println() and pass in the parameter f.length().

Since we didn't specify the path in the parameter passed into the File object, the Java program looks in the current directory, the one storing this Java file, to look for the file name books.pdf.

If you want to specify a directory other than the current directory, then you will have to specify the complete path.

Since this differs according to what operating system you are using, this is the only part of Java that becomes platform dependent.

In a Windows computer, you normally specify the drive you are using with a letter such as the C drive and then specify the path from there to the file that you want to retrieve.

So if you have an object you want to check to see whether it is a file in the C:\Users\ directory, then you would write this into the string as "C:\\Users\\"

This is because "\" is an escape character; it's used for escaping strings. To show "\" in a string, you would have to put double forward slashes "\\".

So this is shown below.






How to Get the Value in Bits, Kilobytes or Megabytes

So, as stated, the length() function gets the size of a file in bytes.

So to get the file size in bits, you simply multiply the number of bytes by 8, since there are 8 bits in a byte.

To get the number of kilobytes, you divide the number of bytes by 1000.

To get the number of megabytes, you divide the number of bytes by 1000000.

This is shown in the following program below.



And this is all that is required to get the size of a file using Java.


HTML Comment Box is loading comments...