Get Size of Directory in Java



A group of files combined stored at a common location is known as a "Directory". A directory not only contains a group of files but also it can contain a group of other directories as well. A directory is also known as a "Folder". Directories are a fundamental component of file systems and are used by different operating systems to provide a logical organization of files and to help us perform file management tasks such as searching, sorting, and moving files. In this section, we are going to write a Java program to get the size of a directory.

What is a File?

A file is a collection of information that may contain data such as text information, images, audio, videos, and program code. These can be accessed by any software application to perform actions like read, write, update, delete, etc.

Performing Operations on Files in Java

In Java, we have two packages to work with files. 

java.io package

java.io package helps for working with files. It helps to create, modify, delete, and get information like size, last modified date, and so on files and directories. 

This package provides various classes, interfaces, and methods. Now, let us look into different classes and interfaces of the java.io package.

  • File class ? This class helps to work on files and directories and helps with basic operations like creation, deletion, and manipulation.

  • FileInputStream ? This class is used to write data to files.

  • FileOutputStream ? This class is used to read data from files.

java.nio package

java.nio package is more efficient for file operations. It helps to work with paths, files, and file system and provides basic operations to create, delete, copy, and move files. This package helps with getting file attributes like size, created date, owner, and permissions.

This package provides various classes, interfaces, and methods. Now, let us look into different classes and interfaces of java.nio package

  • File ? This class helps with basic file I/O operations such as creating, deletion, getting file attributes, and modifying files.

  • Path ? This class helps work with the path of the directory and files.

  • FileSystem ? This class helps to work with both files and paths. 

Syntaxes

  • Creating File Object

File objectname=new File("path of file");

This method is used to return the absolute path of a file from root directories. It returns a String which gives us the absolute path of the file.

String absolutePath = fileObject.getAbsolutePath(); 

This method returns an array of files present in the directory. 

File directory = new File("/path/to/directory");
// Get an array of File objects representing the files in the directory
File[] files = directory.listFiles();

This method returns a boolean value true if the object is a file.

// Create a File object representing a file
File file = new File("/path/to/file.txt");
// Check if the File object represents a file
boolean value = file.isFile()   
// returns true 
// Create a File object representing a file
File file = new File("/path/to/file.txt");
// Check if the File object represents a file
boolean value = file.isFile()   
// returns true 

This returns the size of the file in bytes.

// Create a File object representing a file
File file = new File("/path/to/file.txt");
// Get the length of the file in bytes
long length = file.length();
  • get()

This method helps to convert string path or URL to path

// Create a Path object from a string path
Path path = Paths.get("/path/to/file.txt");
  • walk()

This method is used to find all the files in a directory.

// Create a Path object representing the starting directory
Path start = Paths.get("/path/to/starting/directory");


// Traverse the file tree and print the names of all files and directories
try (Stream<Path> stream = Files.walk(start)) {
   stream.forEach(path -> System.out.println(path));
}
  • mapToLong()

This method is used to convert file size to bytes.

// Create an array of files
File[] files = {new File("/path/to/file1.txt"), 
new File("/path/to/file2.txt"), 
new File("/path/to/file3.txt")};


// Calculate the total size of the files
long totalSize = Arrays.stream(files)
.mapToLong(file -> file.length())
.sum();

We will now discuss different approaches in Java to get the size of the Directory.

Approach 1: Using java.io package

We in this example use the java.io package in java and find the size of a directory. Now, let us look into the algorithm to be followed and the implementation of the Java code. 

Steps

  • Create a directory and define a method for getting directory size.

  • Initialize value for size as 0

  • For all objects in the directory, if the object is a file then add the size to directory size. Else call the directory size method again and print the size

Example

In this example, we used the java.io package and used File class. We use a custom method called "DirectorySizeCalculation" which returns the size of the Directory and we call this function in the main() function and pass the created file object ?file'. Thus the returned value is stored in the ?length' variable and it is printed.

import java.io.File;
public class Main {
   public static long DirectorySizeCalculation(File file) {
      long size = 0;
      for (File x : file.listFiles()) {
         if (x.isFile()) {
            size = size+ x.length();
         } else {
            size = size + DirectorySizeCalculation(x);
         }
      }
      return size;
   }
   public static void main(String[] args) {
      try {
         File file = new File("C:/example-directory");
         long length = DirectorySizeCalculation(file);
         System.out.println("Size of directory  is  " + length + "  bytes");
      } catch (Exception e) {
         System.out.println("An error occurred: " + e.getMessage());
      }
   }
}

Output

Size of directory is 950 bytes

Approach 2: Using java.nio package

We in this example use java.nio package in Java and find the size of the directory. Now, let us look into the algorithm to be followed and the implementation of the Java code.

Steps

We follow the below steps in this approach:

  • Create a path and find all the files in a directory using Files.walk()

  • Check if a file is a file or directory using the filter() method

  • Convert the size of a file to bytes using the mapToLong() method and add to sum using sum().

Example

In this example, we used the java.nio package and used Files, Path, and Paths class. We use Paths.get() and get the path of a file. On getting the path we use the ?walk()' method in the Files class and get all the files iteratively and then we use the ?filter()' method and filter out all the files and then use the ?mapToLong()' method converts all the files to bytes and at last we use the ?sum()' method to find the sum of size all the files and store this in a ?length' variable. Then we will print the Size of the Directory by using the ?length' variable.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
   public static void main(String[] args) throws IOException {
      Path path = Paths.get("C:/example-directory");
      long length = Files.walk(path)
         .filter(p -> p.toFile().isFile())
         .mapToLong(p -> p.toFile().length())
         .sum();
      System.out.println("Size of directory with path " + path + " is " + length + " bytes");
   }
}  

Output

Size of directory with path C:/example-directory is 950 bytes

Thus in this article, we have discussed different approaches to calculating the Size of a Directory using Java programming Language.

Updated on: 2025-01-28T14:57:26+05:30

766 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements