How to Get File Size in Java

Calculating the size of a file is a common task when dealing with file management in Java programming. In this blog post, we will explore different methods to determine the size of a file using Java. 

Method 1: Using java.io.File

The java.io.File class provides a straightforward approach to get the size of a file. 

Here's an example:

import java.io.File;

public class FileSizeExample {
    public static void main(String[] args) {
        File file = new File("path/to/your/file.txt");
        long fileSize = file.length();
        System.out.println("File Size: " + fileSize + " bytes");
    }
}

Method 2: Using java.nio.file.Files

The java.nio.file.Files class in the java.nio.file package offers a modern way to retrieve the size of a file:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesSizeExample {
    public static void main(String[] args) {
        Path path = Paths.get("path/to/your/file.txt");
        try {
            long fileSize = Files.size(path);
            System.out.println("File Size: " + fileSize + " bytes");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Method 3: Using FileInputStream

You can also utilize java.io.FileInputStream to calculate the file size:

import java.io.File;
import java.io.FileInputStream;

public class FileInputStreamSizeExample {
    public static void main(String[] args) {
        File file = new File("path/to/your/file.txt");
        try (FileInputStream fis = new FileInputStream(file)) {
            long fileSize = fis.available();
            System.out.println("File Size: " + fileSize + " bytes");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Conclusion

Whether you opt for the classic java.io.File, the modern java.nio.file.Files, or the FileInputStream approach, these methods provide you with the ability to accurately retrieve file sizes. By mastering these techniques, you can effectively manage and manipulate files of varying sizes in your Java applications.

Comments