nio.File 文件操作

原博客地址:https://blog.csdn.net/LuoZheng4698729/article/details/51697648

Path 类是jdk7新增加的特性之一,用来代替java.io.File类。
之所以新增这个类,是由于java.io.File类有很多缺陷:
1.java.io.File类里面很多方法失败时没有异常处理,或抛出异常
java.io.File.delete()方法返回一个布尔值指示成功或失败但是没有失败原因
2.Path 速度快,方便。

Path 操作

1.删除文件
这里写图片描述
2.遍历目录,不包括子目录的文件

    Path dir = Paths.get("F:\\LZ\\pdf");
    DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
    for(Path path : stream){
        System.out.println(path.getFileName());
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

2.遍历目录,及其子目录下的文件

    Path dir = Paths.get("F:\\LZ\\pdf");
    Files.walkFileTree(dir,new SimpleFileVisitor<Path>(){
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if(file.toString().endsWith(".pdf")){
                System.out.println(file.getFileName());
            }
            return super.visitFile(file, attrs);
        }
    });
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3.创建多级目录

    Path dir = Paths.get("F:\\LZ\\xx\\dd");
    Files.createDirectories(dir);
 
 
  • 1
  • 2

4.创建文件, 不存在则抛出异常

    Path dir = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    Files.createFile(dir);
 
 
  • 1
  • 2

5.文件的复制

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    Path target = Paths.get("F:\\LZ\\xx\\dd\\2.txt");

    //REPLACE_EXISTING:文件存在,就替换
    Files.copy(src, target,StandardCopyOption.REPLACE_EXISTING);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

6.一行一行读取文件

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    BufferedReader reader = Files.newBufferedReader(src,StandardCharsets.UTF_8);
    String line ;
    while((line=reader.readLine()) != null){
        System.out.println(line);
    }
    reader.close();
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7.写入字符串

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    BufferedWriter writer = Files.newBufferedWriter(src, StandardCharsets.UTF_8
            ,StandardOpenOption.APPEND); // 追加
    writer.write("hello word Path");
    writer.close();
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

8.二进制 读写 与字符串类似

  1. 一个方法直接去取字符串 和 二进制流
    // 字符串
    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    for(String line : Files.readAllLines(src)){
        System.out.println(line);
    }
    // 二进制流
    byte[] bytes = Files.readAllBytes(src);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

10.监测是否 目录下的 文件,目录 被修改,创建,或删除.
这里写图片描述

11.读取文件的 最后 1000 个字符
这里写图片描述



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值