How to Get the Size of a File Using 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
In the main method, we create a file object, f, and pass the parameter named path into the this File object.
So at this point in the code, the File object f has the value of books.pdf.
We then call the isFile() function through the if statement.
The function is f.isFile(). This function returns a boolean value of either true or false. If the object is a file in the directory, it returns true. If the object is not a file, it returns false. We output the appropriate message based on this boolean value.
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 object that you want to check is a file.
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 "\\".
And this is all that is required to check whether an object of the File class
is a file or not.
Related Resources
How to Check if a File Exists Using Java
How to Check if an Object is a File Using Java
How to Check if a File is a Directory Using Java
How to Create a New File Using Java
How to Rename a File Using Java
How to Delete a File Using Java
How to Create a New Directory Using Java
How to List All Files in a Directory Using Java
How to Read a File Using Java
How to Write Data to a File Using Java