获取整个工程根目录
String rootDirectory = System.getProperty("user.dir");Path root = Paths.get(rootDirectory);System.out.println(root.toString());
路径操作,读取目录结构,父目录,子目录,拼接目录
System.out.println(STR."parent dir:\{root.getParent().toString()}");String[] children = root.toFile().list();for (String dir : children) {Path pathResolve = root.resolve(dir);System.out.println(pathResolve.toString());}
创建,写文件
Path demo = root.resolve("demo.txt");Path file = Files.createFile(demo);Files.writeString(file, "hello truman\n");Files.writeString(file, "hello du\n", StandardOpenOption.APPEND);
读取文件,文件属性,复制文件
List<String> lines = Files.readAllLines(file);for (String line : lines) {System.out.println(line);}BasicFileAttributeView fileAttributeView = Files.getFileAttributeView(file, BasicFileAttributeView.class);BasicFileAttributes basicFileAttributes = fileAttributeView.readAttributes();System.out.println(STR."file create time:\{basicFileAttributes.creationTime()}");Files.copy(path, pathBackup);
遍历所有目录和子目录,删选.txt 文件
try(Stream<Path>pathStream = Files.walk(root);) {pathStream.filter(path -> path.toString().endsWith(".txt")).forEach(System.out::println);}
删除文件
Files.deleteIfExists(demo);