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 get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024