NIO(二)--file与path的结合使用

来源:互联网 发布:建站平台系统源码 编辑:程序博客网 时间:2024/05/18 03:36

遍历目录树:

public static void main(String[] args) throws IOException {    Path p4=Paths.get("E:\\版本控制\\服务端" );    Files.walkFileTree(p4,new FindFile());} private static class  FindFile extends SimpleFileVisitor<Path>{        @Override        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {            if (file.toString().endsWith("cs")){                System.out.println(file.getFileName());            }            return FileVisitResult.CONTINUE;        }    }

文件创建:

 Path p4=Paths.get("E:\\版本控制1\\服务端\\1.txt" );        Path p5=p4.getRoot().resolve(p4.subpath(0,p4.getNameCount()-1));        Files.createDirectories(p5);        if (Files.notExists(p4))            Files.createFile(p4);

文件删除以及属性设置(windows下):

Path p4=Paths.get("E:\\版本控制1\\服务端\\1.txt" );        Path p5=p4.getRoot().resolve(p4.subpath(0,p4.getNameCount()-1));        Files.createDirectories(p5);        DosFileAttributeView perms =Files.getFileAttributeView(p4,DosFileAttributeView.class);        if (Files.exists(p4)){            perms.setReadOnly(false);            Files.delete(p4);        }        Files.createFile(p4);        perms.setReadOnly(true);        System.out.println(perms.readAttributes().isReadOnly());

文件复制:

Path p4=Paths.get("E:\\版本控制1\\服务端\\1.txt" );        Path p6=Paths.get("E:\\版本控制1\\服务端\\2.txt" );        Files.copy(p4,p6,StandardCopyOption.COPY_ATTRIBUTES);//StandardCopyOption.COPY_ATTRIBUTES如果文件已经存在,复制会失败//StandardCopyOption.REPLACE_EXISTING不管是否存在,都能复制成功//StandardCopyOption.ATOMIC_MOVE复制失败会回滚,windows下不支持

移动文件(也就是剪切)

        Path p4=Paths.get("E:\\版本控制1\\服务端\\2.txt" );        Path p6=Paths.get("E:\\版本控制1\\2.txt" );        Files.move(p4,p6,StandardCopyOption.REPLACE_EXISTING);
        Path p4=Paths.get("E:\\版本控制1\\服务端\\2.txt" );        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        System.out.println(dateFormat.format(Date.from(Files.getLastModifiedTime(p4).toInstant())));        System.out.println(Files.isSymbolicLink(p4));        System.out.println(Files.size(p4));        System.out.println(Files.readAttributes(p4,"*"));//读取所有属性
原创粉丝点击