Java IO Tutorial

How to get file size in Java

In Java, we can use Files.size(path) to get the size of a file in bytes.


  // size in bytes
  long bytes = Files.size(path);

1. Files.size (NIO)

This example uses NIO Files.size(path) to print the size of an image file (140 kb).

GetFileSize.java

package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class GetFileSize {

    public static void main(String[] args) {

        // this image is around 140kb
        String fileName = "/home/mkyong/Pictures/temp.png";
        printFileSizeNIO(fileName);

    }

    public static void printFileSizeNIO(String fileName) {

        Path path = Paths.get(fileName);

        try {

            // size of a file (in bytes)
            long bytes = Files.size(path);
            System.out.println(String.format("%,d bytes", bytes));
            System.out.println(String.format("%,d kilobytes", bytes / 1024));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Output


143,041 bytes
139 kilobytes

2. File.length (Legacy IO)

In the old days (Before Java 7), we can use the legacy IO File.length() to get the size of a file in bytes. This example will format the bytes up to the yottabytes, just for fun.

GetFileSize2

package com.mkyong.io.howto;

import java.io.File;

public class GetFileSize2 {

    public static void main(String[] args) {

        String fileName = "/home/mkyong/Pictures/temp.png";
        printFileSize(fileName);
    }

    public static void printFileSize(String fileName) {

        File file = new File(fileName);

        if (file.exists()) {

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

            long kilobytes = (bytes / 1024);
            long megabytes = (kilobytes / 1024);
            long gigabytes = (megabytes / 1024);
            long terabytes = (gigabytes / 1024);
            long petabytes = (terabytes / 1024);
            long exabytes = (petabytes / 1024);
            long zettabytes = (exabytes / 1024);
            long yottabytes = (zettabytes / 1024);

            System.out.println(String.format("%,d bytes", bytes));
            System.out.println(String.format("%,d kilobytes", kilobytes));
            System.out.println(String.format("%,d megabytes", megabytes));
            System.out.println(String.format("%,d gigabytes", gigabytes));
            System.out.println(String.format("%,d terabytes", terabytes));
            System.out.println(String.format("%,d petabytes", petabytes));
            System.out.println(String.format("%,d exabytes", exabytes));
            System.out.println(String.format("%,d zettabytes", zettabytes));
            System.out.println(String.format("%,d yottabytes", yottabytes));

        } else {
            System.out.println("File does not exist!");
        }

    }

}

Output

Terminal

143,041 bytes
139 kilobytes
0 megabytes
0 gigabytes
0 terabytes
0 petabytes
0 exabytes
0 zettabytes
0 yottabytes

As the time of writing, the disk storage is still in terabytes, is petabytes hard disk or SSD exists?

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
16 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
umberto
7 years ago

i love you mkyong i think about you at night 😉

Rajeevan
6 years ago

Wil it loads the file to the memory? Does calling file.length() iterate through each byte of the file? I mean, will it take the same time to call file.length() & print the chars in the file?

Reyner
9 years ago

Really nice and helpful sir, thank you once again

Steve
9 years ago

Very helpful… Thanks for creating this!

@Kjellski
10 years ago

Hey mkyong,

I just wanted to tell you that I keep getting to your posts and I love them.
Always deliver, simple clean and reproducable results. Keep the work up, even
the simple tricks sometimes help.

Thanks,
@kjellski

Scott Duncan
10 years ago

Love your posts. Always helpful.

Lance
1 year ago

Very helpful. How would we do this if the file resided somewhere on the internet, such as a JS file and get the size of the file via the url/filepath?

ShiMa
1 year ago

Hi, your posts are clear thanks alot, I have a problem here I am using java. security.Signature, I have created a signature with DSA for string characters, I need to print the size of that signature however, it gives me 64 always , even the signature with 10 character , any advice will be approciated ..
Here is my code:
      try {
                //Remetente Gera Assinatura Digital para uma Mensagem
                  SignerUser  signer = new SignerUser ();
                  String message =(“GTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTTGTTTAAGCACTGGTGATTCTGTTCACTAGTGCATACACTGATATTTAAGTGGTGTTCCGTCACTGCTTATTGGGCAAGTGTTGTATTTTCATTCCTT”);
                  long start = System.currentTimeMillis();                
                byte[] sign = signMessage(message.getBytes(), signer.getPrivateKey());
                long time = System.currentTimeMillis() – start;
                 String s = Base64.getEncoder().encodeToString(sign);
               
                //Guarda Chave Pública para ser Enviada ao Destinatário
                PublicKey pubKey = signer.getPubKey();
                System.out.println(“signature of the massage is:  “ + sign );
                System.out.println(“signature running  “ +time +” ms” );
                System.out.println(s.length());

test
2 years ago

Interesting. Files.size() throws IOException while File.length() doesn’t. They must have been implemented differently.

lily
6 years ago

Then where i can make changes in this code to make it measure the entered text by user ?

Adam Smith
7 years ago

I have a yottabyte of porn on my laptop

nishant
8 years ago

Very helpful sir…keep up the good work