Last Updated:

How do I know the file extension & Size of file in Java?

Recently, I have a lot of work with files in Java, especially often I have to programmatically recognize the file extension, so I decided to share an easy way to do it in Java.

Table of Contents

How do I know the file extension in Java?

How to find out the file extension in Java. Theory

I often have to handle files differently depending on its type, but there's not a single built-in method for getting the file extension. That is why here I offer you my simple tested way to get the file extension in Java.

java.io.File

How to get the file extension. Practice

This program shows in the work the method of obtaining the file extension:

The result of the program:

Note that here I haven't checked if the file is file at all. Keep in mind that in real programs you should check that the file exists. And only after that to carry out some manipulations with this file.

 

How to know Size of a file in Java?

Today we will learn a way to get the file size in Java. As always, we will first describe what, how and why in theory, and then in practice we will consolidate the knowledge.

How to find out the file size. Theory

The java.io.File method can be used to get the size of a file. This method returns the size of the file in bytes.length()

When using the method, you should always check whether the file exists or not. If the file does not exist, this method returns zero.length()

How to find out the file size in Java. Practice

Here is an example of a simple program that calculates the size of a Java file:

And here is the result of the program: