Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

15.3. Files

15.3.1. 删除文件

			
package cn.netkiller.test;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileDirectory {
    public static void main(String[] args) throws IOException {
        //如果文件不存在,抛出NoSuchFileException
        //如果文件夹里面包含文件,抛出DirectoryNotEmptyException
        Path path = Paths.get("D:\\data\test");
        Files.delete(path);   //返回值void
        
    }
}
			
			
			
    //如果文件不存在,返回false,表示删除失败(文件不存在)
	//如果文件夹里面包含文件,抛出DirectoryNotEmptyException
    private static void deleteIfExists() throws IOException {
        Path path = Paths.get("D:\data\test1");
        boolean result = Files.deleteIfExists(path);
        System.out.println(result);
    }

    private static void deleteDirectoryStream(Path path) {
        try {
            Files.delete(path);
            System.out.printf("删除文件成功:%s%n",path.toString());
        } catch (IOException e) {
            System.err.printf("无法删除的路径 %s%n%s", path, e);
        }
    }
    
    // 递归删除目录,使用Files.walk遍历文件夹,然后返回 Stream<Path>,接着递归调用删除目录方法
    private static void testDeleteFileDir6() throws IOException {
        createMoreFiles();
        Path path = Paths.get("D:\data\");

        try (Stream<Path> walk = Files.walk(path)) {
            walk.sorted(Comparator.reverseOrder())
                    .forEach(DeleteFileDir::deleteDirectoryStream);
        }

    }
			
			

walkFileTree与FileVisitor配合使用,walkFileTree方法遍历整个文件目录树,使用FileVisitor处理遍历结果(文件或文件夹)

			
	// FileVisitor的postVisitDirectory方法,注意方法中的“post”表示“后去做……”的意思,所以用来文件都处理完成之后再去处理文件夹,所以使用这个方法删除文件夹就可以有效避免文件夹内容不为空的异常,因为在去删除文件夹之前,该文件夹里面的文件已经被删除了。
    private static void walkFileTree() throws IOException {
        Path path = Paths.get("D:\\data");

        Files.walkFileTree(path,
                new SimpleFileVisitor<Path>() {
                    // 先去遍历删除文件
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.delete(file);
                        System.out.printf("删除文件 : %s%n", file);
                        return FileVisitResult.CONTINUE;
                    }

                    // 再去遍历删除目录
                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        System.out.printf("删除文件夹: %s%n", dir);
                        return FileVisitResult.CONTINUE;
                    }

                }
        );

    }			
			
			

15.3.2. 创建目录和文件

			
    private  void createMoreFiles() throws IOException {
        Files.createDirectories(Paths.get("D:\data\test1\test2\test3\test4\test5\"));
        Files.write(Paths.get("D:\data\test1\test2\test2.log"), "hello".getBytes());
        Files.write(Paths.get("D:\data\test1\test2\test3\test3.log"), "hello".getBytes());
    }