# How to get a file size in Java

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Dec 7, 2019. Topics: Java.
Canonical URL: https://attacomsian.com/blog/java-get-file-size

> A short tutorial to learn how to get a file size in Java.

In Java 7+, you can use the `Files.size()` static method to **get the size of a file in bytes**. Let us say we have a `logo.png` image file of size ~17KB on the file system.

## Using `Files.size()` Method

Here is an example that demonstrates how you can use `Files.size()` from [Java's NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api) to get the file size:

```java
try {
    // get file size in bytes
    long size = Files.size(Paths.get("logo.png"));

    // convert size to KB/MB
    double kb = size / 1024.0;
    double mb = kb / 1024.0;

    // print size
    System.out.println("Bytes: " + size);
    System.out.println("KB: " + kb);
    System.out.println("MB: " + mb);

} catch (IOException ex) {
    ex.printStackTrace();
}
```

The above program will output the following:

```bash
Bytes: 17335
KB: 16.9287109375
MB: 0.016531944274902344
```

> **Note:** The size of a file may differ from the actual size on the file system due to compression, support for sparse files, or other reasons.

## Using `File.length()` Method

If you can using an older version of Java (< 7), you can still get the file size simply using `File.length()` as shown  below:

```java
// create a file instance
File file = new File("logo.png");

// check if file exist (recommended)
if (file.exists()) {

    // get file size in bytes
    long size = file.length();

    // convert size to KB/MB
    double kb = size / 1024.0;
    double mb = kb / 1024.0;

    // print size
    System.out.println("Bytes: " + size);
    System.out.println("KB: " + kb);
    System.out.println("MB: " + mb);

}
```

## Further Reading

You may be interested in other Java I/O articles:

* [Reading and Writing Files in Java](https://attacomsian.com/blog/java-read-write-files)
* [How to Read and Write Text Files in Java](https://attacomsian.com/blog/java-read-write-text-files)
* [How to Read and Write Binary Files in Java](https://attacomsian.com/blog/java-read-write-binary-files)
* [Reading and Writing Files using Java NIO API](https://attacomsian.com/blog/java-read-write-files-nio-api)
* [How to read a file line by line in Java](https://attacomsian.com/blog/how-to-read-a-file-line-by-line-in-java)
