Files.size Method (Get File Size)
This page was last reviewed on Jan 24, 2024.
Dot Net Perls
Files.size. What is the size in bytes of a file? In Java this can be determined with the Files class, but we first need to create a Path.
To create a path, we can use the getPath() method with any number of String arguments. Then we can invoke the Files.size method with this path.
Example. This program gets the file size of a file in the programs directory with the name example.txt. When you run this program, be sure to change the path to one that exists.
Step 1 We get a Path instance. We need a FileSystem to get a path, so we get the default with FileSystems getDefault().
Step 2 We use a try-catch block and pass the path we created to the Files.size method.
Step 3 If the file did not exist, an IOException will be encountered. In this situation we just set the size to 0.
Step 4 We print the size of the file. On the test system, the example.txt file as reported by macOS was 20 bytes.
import java.io.*; import java.nio.file.*; public class Program { public static void main(String[] args) { // Step 1: get the default file system, and get a path in the programs directory. var path = FileSystems.getDefault().getPath("programs", "example.txt"); // Step 2: pass the path to the Files.size method. long size; try { size = Files.size(path); } catch (IOException ex) { // Step 3: if an IOException occurred, just use the size 0. size = 0; } // Step 4: print the size of the file. System.out.println(size); } }
Summary. To get the size of a file in Java, we invoke the Files.size method. If you haven't used this method before (or recently), creating the required Path can be a challenge.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 24, 2024 (new).
© 2007-2024 Sam Allen.