Java SE 7发行版中引入的Path类是java.nio.file
·包的主要入口点之一,下面将列出了在NIO中创建Path的6种方法。
定义绝对Path
让我们看下面的代码示例。
public class PathTest {
public static void main(String[] args) {
Path absolutePath = Paths.get("C:/temp/a/b/sample.txt");
Path absolutePath1 = Paths.get("C:/temp/a/b", "sample.txt");
Path absolutePath2 = Paths.get("C:/temp", "a/b", "sample.txt");
Path absolutePath3 = Paths.get("C:/temp", "a", "b", "sample.txt");
System.out.println(absolutePath);
System.out.println(absolutePath1);
System.out.println(absolutePath2);
System.out.println(absolutePath3);
}
}
运行结果
C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt
C:\temp\a\b\sample.txt
定义相对于根目录的Path
使用字符/
开头(windows也可以使用c:/
),让我们看下面的代码示例。这里使用/
public class PathTest2 {
public static void main(String[] args) {
Path relativePath1 = Paths.get("/temp/a/b/sample.txt");
System.out.println(relativePath1.toAbsolutePath());
}
}
运行结果
C:\temp\a\b\sample.txt
定义相对于当前工作目录的Path
让我们看下面的代码示例。
public class PathTest3 {
public static void main(String[] args) {
Path relativePath1 = Paths.get("config", "test.properties");
System.out.println(relativePath1.toAbsolutePath());
}
}
运行结果
C:\temp-workspace\workspace\daytest\config\test.properties
定义URI方法的Path
让我们看下面的代码示例。
public class PathTest4 {
public static void main(String[] args) {
URI uri = URI.create("file:///temp/a/b/sample.txts");
String scheme = uri.getScheme();
// scheme类型为:file
if (scheme.equalsIgnoreCase("file")) {
System.out.println(Paths.get(uri).toAbsolutePath());
}
// 不知道scheme类型为:file
for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
if (provider.getScheme().equalsIgnoreCase(scheme)) {
System.out.println(provider.getPath(uri).toAbsolutePath());
break;
}
}
}
}
运行结果
C:\temp\a\b\sample.txts
C:\temp\a\b\sample.txts
使用File Systems定义获取Path
让我们看下面的代码示例。
public class PathTest5 {
public static void main(String[] args) {
Path relativePath1 = FileSystems.getDefault().getPath("/temp/a/b/sample.txts");
System.out.println(relativePath1.toAbsolutePath());
}
}
运行结果
C:\temp\a\b\sample.txts