简介

  • java7中文件IO发生了很大的变化,专门引入了很多新的类

    import java.nio.file.DirectoryStream;
    import java.nio.file.FileSystem;
    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.nio.file.attribute.FileAttribute;
    import java.nio.file.attribute.PosixFilePermission;
    import java.nio.file.attribute.PosixFilePermissions;
    
  • 等等,来取代原来的基于java.io.File的文件IO操作方式
  • 其中Path就是用来取代File的,我们以前用File包装文件路径、构建文件,现在用Path则可以使用java7中的新特性来表示一个文件路径或者一个文件。

    //以当前路径作为Path对象
    Path p = Paths.get("."); //使用get来从一个路径字符串构造Path对象
    //使用传入的字符串返回一个Path对象
    Path p2 = Paths.get("D","ReviewIO","URL");
    //等同于
    Path p2 = Paths.get("D:\\ReviewIO\\URL");
    //对应的路径
    System.out.println("p对象的对应路径:" + p.toString());
    System.out.println("p2对象的对应路径:" + p2.toString());
    //路径数量是以路径名的数量作为标准
    System.out.println("p路径数量:" + p.getNameCount());
    System.out.println("p2路径数量:" + p2.getNameCount());        
    //获取绝对路径
    System.out.println("p绝对路径:" + p.toAbsolutePath());
    System.out.println("p2绝对路径:" + p2.toAbsolutePath());
    //获取父路径
    System.out.println("p父路径:"  + p.getParent());
    System.out.println("p2父路径:" + p2.getParent());
    //获取p2对象的文件名或者文件目录名
    System.out.println(p2.getFileName());
    //通过Path对象返回一个分隔符对象
    Spliterator<Path> split = p2.spliterator();
    
  • 与File、URI的转换

    URI u = URI.create("file://C:/Xmp/dd");        
    Path p = Paths.get(u);
    
    File file = new File("C:/my.ini");
    Path p1 = file.toPath();
    p1.toFile();
    file.toURI();
    
  • 检测文件是否存在

    Path target2 = Paths.get("C://mystuff.txt");
    try {
        if(!Files.exists(target2))
            Files.createFile(target2);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
  • 读取字符文件

    BufferedReader reader=Files.newBufferedReader(Paths.get("D://test4.txt"),StandardCharsets.UTF_8); //比原来的FileInputStream,然后BufferedReader包装,等操作简单的多了
    char[] buffer=new char[20];
    String info=null;
    int len=0;
    while ((info=reader.readLine())!=null){ //因为reader读的只能是纯文本,纯文本大多都有分行
        System.out.println(info);
    }
    reader.close();
    
  • 写字符到文件

    BufferedWriter writer=Files.newBufferedWriter(Paths.get("D://test4e.txt")); //不指定编码也可以
    writer.write("测试文件写操作");
    writer.flush();
    writer.close();
    

    Files类

  • 里面的读写、创建文件夹之类的静态方法比File要快
  • Files.createDirectory(Path path)

    Path path = Paths.get("data/subdir");
    try {
        Path newDir = Files.createDirectory(path);
    } catch(FileAlreadyExistsException e){
        // the directory already exists.
    } catch (IOException e) {
        //something else went wrong like the parent doesn`t exsit
        e.printStackTrace();
    }
    
  • File.copy()

    Path sourcePath      = Paths.get("data/logging.properties");
    Path destinationPath = Paths.get("data/logging-copy.properties");
    try {
        Files.copy(sourcePath, destinationPath); //把一个文件拷贝到另一个位置
    } catch(FileAlreadyExistsException e) {
        //destination file already exists  //如果补上第三个参数:StandardCopyOption.REPLACE_EXISTING则可以强制覆盖已存在的文件
    } catch (IOException e) {
        //something else went wrong
        e.printStackTrace();
    }
    
  • Files.move():移动文件也有重命名的效果

    Path sourcePath      = Paths.get("data/logging-copy.properties");
    Path destinationPath = Paths.get("data/subdir/logging-moved.properties");
    
    try {
        Files.move(sourcePath, destinationPath,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        //moving file failed.
        e.printStackTrace();
    }
    
  • 指定强制覆盖还是报FileAlreadyExistsException的话可能是destinationPath开了流忘记关了
  • Files.delete(path):删除文件或目录,注意,目录也可以