NIO实用API

123 阅读1分钟

批量删除文件-walkFileTree


   /**
     * 下面是拿删除所有目录以及文件举的例子
     * 此方法需要重写SimpleFileVisitor,对目录、文件进行操作
     * 执行方法是有序的,从【进入目录之前->进入目录操作每个文件->结束操作并且要退出目录之前】
     */
    private void handleFileTree(){
        Files.walkFileTree(Paths.get("xxx"),new SimpleFileVisitor<Path>(){

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // 这里是到达目录,还未进目录时的情况
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                // 进入此方法,意味着可以遍历的操作每一个文件,当前就是一个删除每个文件的例子
                Files.delete(file);
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // 进入此方法,是文件遍历后的尾期,可以对此目录进行操作,故写一个删除方法,单做例子
                Files.delete(dir);
                return super.postVisitDirectory(dir, exc);
            }
        });
    }

批量拷贝文件-walk

private void copyFiles(){
        String source = "d:\\123";
        String target = "d:\\456";
        
        Files.walk(Paths.get(source)).forEach(path -> {
            // 更换路径
            String targetName = path.toString().replace(source,target);
            if (Files.isDirectory(path)){
                // 如果是目录,就调用复制目录的方法
                Files.createDirectory(Paths.get(targetName));
            }else if (Files.isRegularFile(path)){
                // 如果是文件,就调用复制文件的方法
                Files.copy(path,Paths.get(targetName));
                
            }
        });
    }

文件写入写出

private static voidtransferTo(){
    try(
            FileChannel from =new FileInputStream("1.txt").getChannel();
            FileChannel to =new FileOutputStream("2.txt").getChannel();
            ){
		//底层零拷贝 效率会更高
		from.transferTo(0,from.size(),to);
        }catch(Exception e){
        e.printStackTrace();
    }

}

文件操作

Path path = Paths.get("D:\\down");

//判断文件是否存在
System.out.println(Files.exists(path));
//创建单层目录
Files.createDirectory(path);
//创建多层目录
Files.createDirectories(path);
// 文件拷贝,如果已存在,会抛异常
Files.copy(source,target);
// 如果希望覆盖
Files.copy(source,target, StandardCopyOption.REPLACE_EXISTING);
// 移动文件
Files.move(source,target, StandardCopyOption.ATOMIC_MOVE);
// 删除文件/目录,不存在会报错
Files.delete(target);