Java Program to get Size of Directory


A group of files combined stored at a common location is known as “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 helps us to 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?

File is a collection of information which may contain data such as text information, images, audio, videos, program code. These can be accessed by any software applications 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 java.io package.

  • File − This class helps to work on files and directories and helps with basic operations like creation, deletion, 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, file system and provides basic operations to create, delete, copy, move files. This package helps with getting file attributes like size, created date, owner, 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 as creating, deletion, getting file attributes, modifying files.

  • Path − This class helps working with 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");
  • getAbsolutePath()

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

String absolutePath = fileObject.getAbsolutePath();
  • listFiles()

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();
  • isFile()

This method returns 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 
  • length()

// 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 Size of Directory.

Approach-1: Using java.io package

We in this example use the java.io package in java and find the size of directory. Now, let us look in to the algorithm to be followed and 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 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 Directory and we call this function in the main() function and pass the created file object ‘file’. Thus the returned value is stored in ‘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 the java.nio package in java and find the size of directory. Now, let us look in to the algorithm to be followed and 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 file or directory using filter() method

  • Convert the size of file to bytes using 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 path of a file. On the getting the path we use the ‘walk()’ method in Files class and get all the files iteratively and then we use the ‘filter()’ method and filter out all the files and then use ‘mapToLong()’ method converts all the files to bytes and 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 Directory by using ‘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 of calculating the Size of Directory using Java programming Language.

Updated on: 11-Apr-2023

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements