Java File Size with Files.size()

Files class have the Files.size() method to determine the size of the file. This is the most recent API and it is recommended for new Java applications.

Java file size with Files

The code example determines the file size using the Files' size() method.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaFileSizeExample {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/words.txt";

        Path filePath = Paths.get(fileName);
        long fileSize = Files.size(filePath);        

        System.out.format("The size of the file: %d bytes", fileSize);
    }
}
Output:
The size of the file: 200 bytes

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments