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);
}
}20
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.