NIO.2 把位置(由Path表示)的概念和物理文件系统的处理(比如复制一个文件)分得很清楚,物理文件系统的处理通常由Files辅助类实现;

    Path Path类中的方法可以用来获取路径信息,访问路径中的各元素,将路径转换为其他形式,或
    提取路径中的一部分。有的方法还可以匹配路径字符串以及移除路径中的冗余项

    Paths 工具类,提供返回一个路径的辅助方法,比如get(String first,String… more)和get(URI uri)

    FileSystem 与文件系统交互的类,无论是默认的文件系统,还是通过统一资源标识(URI)获取的可选
    文件系统

    FileSystems 工具类,提供各种方法,比如其中用于返回默认文件系统的FileSystems.getDefault()

    Path不一定代表真实的文件或目录,用Files中的功能来检查文件是否存在,并对它进行处理

    1. public class PathDemo {
    2. public static void main(String[] args) throws IOException {
    3. //从Path中获取信息
    4. Path listing = Paths.get("D:\\work\\zk\\opensource\\javase");
    5. System.out.println("File Name ["+listing.getFileName()+"]");
    6. System.out.println("Number of Name Elements in the Path ["+listing.getNameCount()+"]");
    7. System.out.println("Parent Path ["+listing.getParent()+"]");
    8. System.out.println("Root of Path ["+listing.getRoot()+"]");
    9. //创建一个Path
    10. Path filePath = Paths.get("./PathDemo.java");
    11. boolean exists = Files.exists(filePath);
    12. System.out.println(exists);
    13. filePath = Paths.get("./src/com/thinking/in/java/course/chapter18/nio/PathDemo.java");
    14. exists = Files.exists(filePath);
    15. System.out.println(exists);
    16. //移除冗余符号("./")
    17. Path normalize = Paths.get("./src/com/thinking/in/java/course/chapter18/nio/PathDemo.java").normalize();
    18. System.out.println(normalize);
    19. //合并一个路径
    20. Path prefix = Paths.get("foo/bar/");
    21. Path completePath = prefix.resolve("gus");
    22. System.out.println(completePath);
    23. }
    24. }