获取目录大小的 Java 程序


一组组合在一起并存储在公共位置的文件被称为“目录”。目录不仅包含一组文件,还可以包含其他目录组。目录也称为“文件夹”。目录是文件系统的一个基本组成部分,不同的操作系统使用它来提供文件的逻辑组织,并帮助我们执行文件管理任务,例如搜索、排序和移动文件。在本节中,我们将编写一个 Java 程序来获取目录的大小。

什么是文件?

文件是信息的集合,可能包含数据,例如文本信息、图像、音频、视频、程序代码。任何软件应用程序都可以访问这些文件来执行读取、写入、更新、删除等操作。

在 Java 中执行文件操作

在 Java 中,我们有两个包可以用来处理文件。

java.io 包

java.io 包有助于处理文件。它有助于创建、修改、删除文件和目录,以及获取文件大小、上次修改日期等信息。

此包提供各种类、接口和方法。现在,让我们了解 java.io 包的不同类和接口。

  • File − 此类有助于处理文件和目录,并有助于执行创建、删除、操作等基本操作。

  • FileInputStream − 此类用于将数据写入文件。

  • FileOutputStream − 此类用于从文件读取数据。

java.nio 包

java.nio 包对于文件操作更高效。它有助于处理路径、文件、文件系统,并提供创建、删除、复制、移动文件的基本操作。此包有助于获取文件属性,例如大小、创建日期、所有者、权限。

此包提供各种类、接口和方法。现在,让我们了解 java.nio 包的不同类和接口。

  • File − 此类有助于执行基本的文件 I/O 操作,例如创建、删除、获取文件属性、修改文件。

  • Path − 此类有助于处理目录和文件的路径。

  • FileSystem − 此类有助于处理文件和路径。

语法

  • 创建文件对象

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

此方法用于从根目录返回文件的绝对路径。它返回一个字符串,其中包含文件的绝对路径。

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

此方法返回目录中存在的文件数组。

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

此方法如果对象是文件,则返回布尔值 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 
  • 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 

此方法返回文件的大小(以字节为单位)。

// 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()

此方法有助于将字符串路径或 URL 转换为路径。

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

此方法用于查找目录中的所有文件。

// 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()

此方法用于将文件大小转换为字节。

// 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();

现在我们将讨论在 Java 中获取目录大小的不同方法。

方法 1:使用 java.io 包

在这个示例中,我们使用 Java 中的 java.io 包来查找目录的大小。现在,让我们了解要遵循的算法和 Java 代码的实现。

步骤

  • 创建一个目录并定义一个用于获取目录大小的方法。

  • 将大小的值初始化为 0。

  • 对于目录中的所有对象,如果对象是文件,则将大小添加到目录大小。否则,再次调用目录大小方法并打印大小。

示例

在这个示例中,我们使用了java.io 包File 类。我们使用一个名为“DirectorySizeCalculation”的自定义方法,该方法返回目录的大小,我们在 main() 函数中调用此函数并传递创建的文件对象“file”。因此,返回值存储在“length”变量中,并将其打印出来。

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());
      }
   }
}

输出

Size of directory is 950 bytes

方法 2:使用 java.nio 包

在这个示例中,我们使用 Java 中的 java.nio 包来查找目录的大小。现在,让我们了解要遵循的算法和 Java 代码的实现。

步骤

在此方法中,我们遵循以下步骤:

  • 创建一个路径,并使用 Files.walk() 查找目录中的所有文件。

  • 使用 filter() 方法检查文件是文件还是目录。

  • 使用 mapToLong() 方法将文件大小转换为字节,并使用 sum() 将其添加到总和中。

示例

在这个示例中,我们使用了java.nio 包Files、Path 和 Paths 类。我们使用 Paths.get() 获取文件的路径。获取路径后,我们在 Files 类中使用“walk()”方法迭代获取所有文件,然后我们使用“filter()”方法过滤所有文件,然后使用“mapToLong()”方法将所有文件转换为字节,最后我们使用“sum()”方法查找所有文件大小的总和,并将此存储在“length”变量中。然后,我们将使用“length”变量打印目录的大小。

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");
   }
}  

输出

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

因此,在本文中,我们讨论了使用 Java 编程语言计算目录大小的不同方法。

更新于:2023年4月11日

浏览量:593

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.