import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaPathExample {
public static void main(String[] args) {
// 创建一个 Path 对象,表示文件或目录的路径
Path path = Paths.get("C:\\Users\\Username\\Documents\\example.txt");
// 打印路径的绝对路径
System.out.println("Absolute Path: " + path.toAbsolutePath());
// 获取文件名
System.out.println("File Name: " + path.getFileName());
// 获取父级路径
System.out.println("Parent Path: " + path.getParent());
// 获取根路径
System.out.println("Root Path: " + path.getRoot());
}
}
java.nio.file.Path 和 java.nio.file.Paths 来处理文件路径。Paths.get() 方法创建一个 Path 对象,表示文件或目录的路径。toAbsolutePath() 方法获取并打印路径的绝对路径。getFileName() 方法获取并打印路径中的文件名部分。getParent() 方法获取并打印路径的父级目录。getRoot() 方法获取并打印路径的根部分。这个示例展示了如何在 Java 中处理和操作文件路径。
下一篇:java.util.date
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站