你的位置:首页 > Java教程

[Java教程]2.2.4 转换 Path


在NIO.2里可以很容易地合并Path,在两个Path中再创建Path或对Path进行比较;

Demo:

import java.nio.file.Path;import java.nio.file.Paths;public class PathConvert {    public static void main(String[] args) {        // 两个[Max OS X]路径    Path path1 = Paths.get("/Users/jinxing/Documents/pathtest/path1");    Path path2 = Paths.get("/Users/jinxing/Documents/pathtest/path2");        // 合并:被合并位置前不加分隔符    Path completePath12 = path1.resolve("ss/ss");        // 距离:两个Path之间的路径    Path path1ToPath2Dir = path1.relativize(path2);        // show    System.out.println(completePath12);    System.out.println(path1ToPath2Dir);        // 比较:equals[Path.toString()-两个字符串之间的比较]    System.out.println(completePath12.toString().equals("/Users/jinxing/Documents/pathtest/path1/ss/ss"));    // 比较:startsWith[Path间比较|完整文件名](以...开头)    System.out.println(path1.startsWith("/Users"));    // 比较:endsWith[Path间比较|完整文件名|前不加分隔符](以...结尾)    System.out.println(path2.endsWith("pathtest/path2"));        // [略]更多比较测试:如Path.equals(Path)      }}

Ran As Java Application:

/Users/jinxing/Documents/pathtest/path1/ss/ss../path2truetruetrue