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.
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.
Path
instance. We need a FileSystem
to get a path, so we get the default with FileSystems
getDefault()
.try-catch
block and pass the path we created to the Files.size
method.IOException
will be encountered. In this situation we just set the size to 0.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
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.