Java中NIO中Path类

[TOC]
文件系统可以通过java.nio.file.FileSystems这个final类来访问。 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;

Path类

  • Path类用来表示文件路径和文件。构架Path对象的方法如下,

    1. 使用final类Paths中的两个static方法

      Path path = Paths.get("C:/", "Abc");
      Path path2 = Path.get("C:\Abc");
      URI u = URI.create("file:///C:/Abc/aa");
      Path p = Paths.get(u);
    2. FileSystems构造

      Path path3 = FileSystems.getDefault().getPath("C:/", "access.log");
    3. File和Path间转换,File与URI转换

      File file = new File("C:/my.ini");
      Path p1 = file.toPath();
      p1.toFile();
      file.toURI();
    4. 创建文件
      java
      Path target = Paths.get("C:\\mystruff.txt");
      try {
      if (!Files.exists(target))
      Files.createFile(target);
      } catch (IOException e) {
      e.printStackTrace();
      }
    5. Files.newBufferedReader读取文件

      try {
          BufferedReader reader = Files.newBufferedReader(Path.get("C:\\my.ini"), StandardCharsets.UTF_8);
          String str = null;
          while((str = reader.readLine()) != null) {
          System.out.println(str);
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
    6. 文件写操作

      try {
          BufferedWriter writer = File.newBufferedWriter(Path.get("C:\\my2.ini"), StandardCharsets.UTF_8);
          writer.write("写操作,测试");
          writer.flush();
          writer.close();
      } catch (IOException e) {
            e.printStackTrace();
      }

引用

Java文件IO操作应该抛弃File拥抱Paths和Files

你可能感兴趣的:(Java)