java中怎么獲取文件夾屬性

小億
111
2024-03-21 15:58:54

在Java中獲取文件夾的屬性可以通過使用File類或者Files類來(lái)實(shí)現(xiàn)。以下是兩種方法的示例:

  1. 使用File類:
import java.io.File;

public class GetFolderProperties {
    public static void main(String[] args) {
        File folder = new File("path/to/folder");

        if (folder.isDirectory()) {
            System.out.println("Folder name: " + folder.getName());
            System.out.println("Folder path: " + folder.getAbsolutePath());
            System.out.println("Folder size: " + folder.length());
            System.out.println("Last modified: " + folder.lastModified());
        } else {
            System.out.println("Not a valid folder path.");
        }
    }
}
  1. 使用Files類:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class GetFolderProperties {
    public static void main(String[] args) {
        Path folderPath = Paths.get("path/to/folder");

        try {
            System.out.println("Folder name: " + folderPath.getFileName());
            System.out.println("Folder path: " + folderPath.toAbsolutePath());
            System.out.println("Folder size: " + Files.size(folderPath));
            System.out.println("Last modified: " + Files.getLastModifiedTime(folderPath));
        } catch (IOException e) {
            System.out.println("Error accessing folder properties: " + e.getMessage());
        }
    }
}

請(qǐng)注意,以上示例中的path/to/folder需要替換為實(shí)際文件夾的路徑。這些示例將打印出文件夾的名稱、絕對(duì)路徑、大小和最后修改時(shí)間等屬性。

0