四时宝库

程序员的知识宝库

(3)NIO 教程-Path, Files的基本使用

Path 用来表示文件路径 ,Paths 是工具类,用来获取 Path 实例,java NIO 的Files可以完全替代以前的文件操作,Files 提供了遍历目录文件方法walkFileTree

Path source = Paths.get("1.txt"); // 相对路径 使用 user.dir 环境变量来定位 1.txt
 
Path source = Paths.get("d:\\1.txt"); // 绝对路径 代表了  d:\1.txt
 
Path source = Paths.get("d:/1.txt"); // 绝对路径 同样代表了  d:\1.txt
 
Path projects = Paths.get("d:\\data", "projects"); // 代表了  d:\data\projects
 
 
//Files
 
//检查文件是否存在
Path path = Paths.get("helloword/data.txt");
System.out.println(Files.exists(path));
 
 
//创建一级目录
Path path = Paths.get("helloword/d1");
Files.createDirectory(path);
 
//创建多级目录用
Path path = Paths.get("helloword/d1/d2");
Files.createDirectories(path);
 
//拷贝文件
Path source = Paths.get("helloword/data.txt");
Path target = Paths.get("helloword/target.txt");
Files.copy(source, target);
 
 
//如果文件已存在,会抛异常 FileAlreadyExistsException
//如果希望用 source 覆盖掉 target,需要用 StandardCopyOption 来控制
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
Files 提供了遍历目录文件方法walkFileTree
//打印文件夹下,目录和文件的个数
public static void main(String[] args) throws IOException {
    Path path = Paths.get("C:\\Program Files\\Java\\jdk1.8.0_91");
    AtomicInteger dirCount = new AtomicInteger();
    AtomicInteger fileCount = new AtomicInteger();
   //path是起点目录,SimpleFileVisitor是你要进行的操作
    Files.walkFileTree(path, new SimpleFileVisitor<Path>(){
        //进入文件夹之前的操作
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
            throws IOException {
            System.out.println(dir);
            dirCount.incrementAndGet();
            return super.preVisitDirectory(dir, attrs);
        }
 
        //遍历到文件的时候
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
            throws IOException {
            System.out.println(file);
            fileCount.incrementAndGet();
            return super.visitFile(file, attrs);
        }
    });
    System.out.println(dirCount); // 133
    System.out.println(fileCount); // 1479
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接