java中怎么获取文件夹属性

2024-04-12

在Java中获取文件夹的属性可以通过使用File类或者Files类来实现。以下是两种方法的示例:

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

请注意,以上示例中的path/to/folder需要替换为实际文件夹的路径。这些示例将打印出文件夹的名称、绝对路径、大小和最后修改时间等属性。