獲取目錄大小的 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.