Friday, January 30, 2026
HomeLanguagesJavaFiles size() method in Java with Examples

Files size() method in Java with Examples

size() method of java.nio.file.Files help us to get the size of a file (in bytes). This method returns the file size, in bytes by taking the path of the file as a parameter. The size may differ from the actual size on the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is implementation-specific and therefore unspecified. 

Syntax:

public static long size(Path path)
                 throws IOException

Parameters: This method accepts a parameter path which is the path to the file. 

Return value: This method returns the file size, in bytes. 

Exception: This method will throw following exceptions:

  1. IOException if an I/O error occurs.
  2. SecurityException in the case of the default provider, and a security manager is installed, its checkRead method denies read access to the file.

Below programs illustrate size(Path) method: 

Program 1: 

Java




// Java program to demonstrate
// Files.size() method
 
import java.io.IOException;
import java.nio.file.*;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // create object of Path
        Path path
            = Paths.get("D:\\GIT_EWS_PROJECTS\\logger"
                        + "\\src\\logger"
                        + "\\GFG.java");
 
        // get File Size
 
        long result;
 
        result = Files.size(path);
 
        System.out.println("File " + path
                           + " Size = "
                           + result + " bytes");
    }
}


Output:

Program 2: 

Java




// Java program to demonstrate
// Files.size() method
 
import java.io.IOException;
import java.nio.file.*;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
 
        // create object of Path
        Path path
            = Paths.get("D:\\User Aman\\"
                        + "Documents\\MobaXterm\\"
                        + "\\ArrayList.docx");
        // get File Size
        long result;
        result = Files.size(path);
 
        System.out.println("File " + path
                           + " Size = "
                           + result + " bytes");
    }
}


Output:

References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html#size?(java.nio.file.Path)

RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS