Java – Get File Size

Java – Get file size

To get the size of a file given by a path in Java, prepare Path object for the given file, call size() method of the java.nio.file.Files class and pass the file path object as argument to the method. The size() method returns a number (of long type) representing the size of the given file.

If filePath is the given file path, then use the following expression to get the size of file.

Files.size(filePath)
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
 
public class Main {
    public static void main(String[] args) {
        try {
            Path filePath = Paths.get("/Users/Vimal/size.txt");
            long fileSize = Files.size(filePath);
 
            System.out.println("File size : " + fileSize);
        } catch (IOException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top