This example will show you how to get the size of a file. To obtain the size of a file you can use the File
‘s length()
method. The length()
method return the file size in bytes.
package org.kodejava.io;
import java.io.File;
public class FileSize {
public static void main(String[] args) {
File file = new File("README.md");
// Get the size of a file in bytes.
long fileSize = file.length();
// Using Java printf() method to print the file size
System.out.printf("File size: %,d bytes.%n", fileSize);
}
}
This will print something like:
File size: 51,981 bytes.
If you want to format the file size in Kilobytes, Megabytes or Gigabytes check the following example How do I create a human-readable file size?.
Latest posts by Wayan (see all)
- How do I compile and execute a JDK preview features with Maven? - December 8, 2023
- How do I sum object property using Stream API? - December 7, 2023
- How do I iterate through date range in Java? - October 5, 2023