You can use the length() method on File which returns the size in bytes.

Answer from Swapnil on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java io › file size in java
File Size in Java | Baeldung
November 29, 2023 - It’s known that : ... We can ... { File file = new File(pathname); if (file.exists()) { // File size in bytes long bytes = file.length(); double kilobytes = (double) bytes / 1024; double megabytes = kilobytes...
🌐
Mkyong
mkyong.com › home › java › how to get file size in java
How to get file size in Java - Mkyong.com
July 23, 2020 - 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(); } } } ... In the old days (Before Java 7), we can use the legacy IO File.length() to get the size of a file in bytes.
🌐
TutorialsPoint
tutorialspoint.com › javaexamples › file_size.htm
How to get a files size in bytes using Java
The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file. bytes : 6119.0 kilobytes : 5.9755859375 megabytes : 0.005835533142089844 gigabytes : 5.698762834072113E-6 terabytes ...
🌐
w3resource
w3resource.com › java-exercises › io › java-io-exercise-9.php
Java - Get file size in bytes, kb, mb
March 2, 2026 - import java.io.File; public class Exercise9 { public static void main(String[] args) { File file = new File("/home/students/test.txt"); if(file.exists()) { System.out.println(filesize_in_Bytes(file)); System.out.println(filesize_in_kiloBytes(file)); System.out.println(filesize_in_megaBytes(file)); } else System.out.println("File doesn't exist"); } private static String filesize_in_megaBytes(File file) { return (double) file.length()/(1024*1024)+" mb"; } private static String filesize_in_kiloBytes(File file) { return (double) file.length()/1024+" kb"; } private static String filesize_in_Bytes(File file) { return file.length()+" bytes"; } }
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-get-file-size
Java get file size | DigitalOcean
August 3, 2022 - Before we look into an example program to get file size, we have a sample pdf file with size 2969575 bytes. Java File length() method returns the file size in bytes. The return value is unspecified if this file denotes a directory. So before calling this method to get file size in java, make ...
🌐
Scaler
scaler.com › home › topics › java › getting file information using java io streams
Getting File Information Using Java IO streams
April 8, 2024 - The File class in java contains a length() method that returns the file size in bytes. To use this method, we first need to create an object of the File class by calling the File(String pathname) constructor.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-get-the-size-of-given-file-in-bytes-kilobytes-and-megabytes
Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes - GeeksforGeeks
March 9, 2021 - bytes : 17,07,91,615 kilobytes : 1,66,788.686 megabytes : 162.8795766 · Note: If you want file size in Gigabytes then again you have to divide mb value by 1024 and so on. But Nowadays we can directly use File.size(path) after Java 7.
🌐
ZetCode
zetcode.com › java › filesize
Java file size - getting file size in Java
package com.zetcode; import java.io.File; public class JavaFileSizeEx { public static void main(String[] args) { String fileName = "src/main/resources/words.txt"; File f = new File(fileName); long fileSize = f.length(); System.out.format("The size of the file: %d bytes", fileSize); } }
Find elsewhere
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-get-file-size-using-Java.php
How to Get the Size of a File Using Java
The Java length() function, when working with files, returns the size of the file in unit bytes.
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-get-the-size-of-given-file-in-bytes-kilobytes-and-megabytes
Java Program to Get the Size of Given File in Bytes, KiloBytes and MegaBytes
June 26, 2024 - For kilo bytes the size is ?sizebytes' ... = new File("C:/example.txt"); if (f.exists()) { long sizebytes = f.length(); System.out.println("File size in bytes is equal to : " + sizebytes); System.out.println("File size in kilobytes is equal to : " + (sizebytes/ 1024)); System.out.p...
🌐
IncludeHelp
includehelp.com › java-programs › get-the-size-of-given-file-in-bytes-kilobytes-and-megabytes.aspx
Java program to get the size of given file in bytes, kilobytes and megabytes
October 27, 2017 - In this program, we are using a file named "includehelp.txt" which is stored in "E:\" in my system, program will get its size in bytes and then we will convert file size in kilobytes and megabytes. import java.io.*; public class ReturnFileSize { public static void main(String[] args) { //create file object. // enter the file name. File file = new File("E:/includehelp.txt"); // calculate the size of the file. long fileSize = file.length(); // return the file size in bytes,KB and MB.
🌐
Tutorialspoint
tutorialspoint.com › java › io › file_length.htm
Java - File length() method
Following is the declaration for java.io.File.length() method − ... The method returns length, in bytes, of the file denoted by this abstract pathname.
🌐
How to do in Java
howtodoinjava.com › home › i/o › java get file size (with examples)
Java Get File Size (with Examples)
May 5, 2024 - File file = new File("..."); // Check Size long bytes = file.length(); //1 long bytes = Files.size(file.toPath()); //2 long bytes = FileUtils.sizeOf(file); //3 // Display Size FileUtils.byteCountToDisplaySize(2333444l);
🌐
Coderanch
coderanch.com › t › 485599 › java › File-length
File length (I/O and Streams forum at Coderanch)
Depends on what you see as "counting". Does it go through the entire file and count bytes that way? No. Does it ask the file system what the file size is? Yes. Keep in mind that the length() is returned as a long for a reason. An int can go up to 2^31 - 1 which is one byte shy of 2GB.
Top answer
1 of 2
7

Logic

You can simplify your logic by testing for the biggest known extension, for example

if (fileSize > 1024 * 1024)
    doMiB();
} else if (fileSize > 1024) {
    doKiB();
} else {
    doByte();
}

Rounding

Don't use Math.round(x / 100.0) * 100. for rounding to two decimal places use the appropriate library function

Argument checking

Don't use default values ("Unknown") for invalid input. If the input to your getFileSize method is not a file, throw an exception

if (!file.isFile()) {
    throw new IllegalArgumentException("Expected argument to be a file");
}

Fast return

This is more personal taste but I prefer to return as soon as possible. If you know the result will be "100.31 KiB" why save it into a local variable instead of returning it immediately?

Conclusion

I would improve the code as followed

private static final DecimalFormat format = new DecimalFormat("#.##");
private static final long MiB = 1024 * 1024;
private static final long KiB = 1024;

public String getFileSize(File file) {

    if (!file.isFile()) {
        throw new IllegalArgumentException("Expected a file");
    }
    final double length = file.length();

    if (length > MiB) {
        return format.format(length / MiB) + " MiB";
    }
    if (length > KiB) {
        return format.format(length / KiB) + " KiB";
    }
    return format.format(length) + " B";
}
2 of 2
6

Use helper functions

The logic performed by your math isn't immediately obvious at a glance. You should introduce a helper function:

static double roundToDecimals(double aValue, int aDecimals){
    ...
}

Even better, just use DecimalFormat:

DecimalFormat df = new DecimalFormat("#.##");
String output = df.format(1.2345678);  // "1.23"

Work in logarithms

You can simplify your determination of the correct suffix by using the logarithm of the file size.

First of note that \$1024 = 2^{10}\$, \$1024*1024 = 2^{20}\$ and so forth. You're checking if \$x < 2^{10}\$ and then if \$x < 2^{20}\$ etc.

It's much easier to take the two-logarithm of \$x\$ and then check \$\log_2(x) < 10\$, \$\log_2(x) < 20\$ etc...

Now if you take \$k=floor(\log_2(x) / 10)\$ you will end up with \$k=0\$ for bytes, \$k=1\$ for KiB, \$k=2\$ for MiB etc. Which means that you can simply index into an array of the suffixes to get the right suffix, then upscale the result to get the correct number of digits.

Like this:

public static double log2(long n){
    // Implement this but without inaccuracies due to FP math. 
    // Just count the number of leading zeros and do the math.
    return (Math.log(n) / Math.log(2));
}

public static String getFileSize(File file) {
    ...
    long logSize = (long)log2(fileSize);
    final String[] suffixes = new String[]{" B", " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB"};

    int suffixIndex = (int) (logSize / 10); // 2^10 = 1024

    double displaySize = fileSize / Math.pow(2, suffixIndex*10);
    DecimalFormat df = new DecimalFormat("#.##");
    return df.format(displaySize) + suffixes[suffixIndex];

Other comments

You should keep your fileSize in long format for accuracy. Also you can move the fileSize variable into the scope of the if where it is initialized and used.

Top answer
1 of 4
1

Try:

    File file =new File("myfile_in_test.java");

    if(file.exists()){

        final double bytes = file.length();
        final double kilobytes = (bytes / 1024);

        System.out.println("bytes : " + bytes);
        System.out.println("kilobytes : " + kilobytes);
    }else{
         System.out.println("File does not exists!");
    }
2 of 4
0

Here is an example which shows that it works just fine.

public class Main {
    public static void main(String[] args) throws IOException, InterruptedException {
        File file = File.createTempFile("deleteme", ".txt");
        file.deleteOnExit();
        Thread main = Thread.currentThread();
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    do {
                        Thread.sleep(200);
                        long length = file.length();
                        System.out.println("File " + file + " is " + length + " bytes long.");
                    } while(main.isAlive());
                    System.out.println("Finished");
                } catch (InterruptedException e) {
                    System.err.println("Interrupted");
                }
            }
        }, "monitor");
        t.start();

        FileOutputStream fos = new FileOutputStream(file);
        for(int i=0;i<2000;i++) {
            fos.write("words words words words words words words words words words words\n".getBytes());
            Thread.sleep(1);
        }
        fos.close();
    }
}

prints something like.

File /tmp/deleteme4214599935706768614.txt is 11880 bytes long.
File /tmp/deleteme4214599935706768614.txt is 23562 bytes long.
File /tmp/deleteme4214599935706768614.txt is 35376 bytes long.
File /tmp/deleteme4214599935706768614.txt is 47256 bytes long.
File /tmp/deleteme4214599935706768614.txt is 59136 bytes long.
File /tmp/deleteme4214599935706768614.txt is 70950 bytes long.
File /tmp/deleteme4214599935706768614.txt is 82830 bytes long.
File /tmp/deleteme4214599935706768614.txt is 94644 bytes long.
File /tmp/deleteme4214599935706768614.txt is 106524 bytes long.
File /tmp/deleteme4214599935706768614.txt is 118338 bytes long.
File /tmp/deleteme4214599935706768614.txt is 130218 bytes long.
File /tmp/deleteme4214599935706768614.txt is 132000 bytes long.
Finished
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-get-the-size-of-a-file-in-java
How to Get the Size of a File in Java? - GeeksforGeeks
February 7, 2024 - Then by using .length() function the length of the file with respective size type(mb,kb and bytes) the size will be displayed. Let's explore how to get the file size using FileChannel Class.