• Index

Path 对象

Last updated: ... / Reads: 47 Edit

Path 对象是 Java 中用于表示文件或目录路径的类。它提供了一组方法来操作和处理文件系统中的路径。 要使用 Path对 象,首先需要导入Java.nio.file包。然后可以通过调用静态方法Paths.get()来创建一个Path对象,该方法接受一个字符串参数,表示文件或目录的路径。

下面是一些常用的Path对象的方法:

  • getFileName(): 返回路径中的文件名部分。
  • getParent(): 返回路径中的父级目录。
  • resolve(String other): 将当前路径与给定的路径合并。
  • toAbsolutePath(): 返回绝对路径。
  • normalize(): 标准化路径,消除冗余的.和..。
  • toString(): 将路径对象转换为字符串表示。

以下是一个简单示例代码,演示如何使用Path对象:

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathExample {
    public static void main(String[] args) {
        // 创建Path对象
        Path path = Paths.get("C:/myfolder/myfile.txt");

        // 获取文件名
        System.out.println("File Name: " + path.getFileName());

        // 获取父级目录
        System.out.println("Parent Directory: " + path.getParent());

        // 合并路径
        Path resolvedPath = path.resolve("subfolder");
        System.out.println("Resolved Path: " + resolvedPath);

        // 转换为绝对路径
        Path absolutePath = path.toAbsolutePath();
        System.out.println("Absolute Path: " + absolutePath);

        // 标准化路径
        Path normalizedPath = Paths.get("C:/myfolder/../myfile.txt").normalize();
        System.out.println("Normalized Path: " + normalizedPath);

        // 转换为字符串
        String pathString = path.toString();
        System.out.println("Path as String: " + pathString);
    }
}

通过运行上述代码,您将看到输出结果显示了各种操作的结果。这只是一个简单示例,Path对象还提供了其他一些方法来处理路径,例如判断文件或目录是否存在、比较路径等。


Comments

Make a comment

  • Index