Java 程序从两个绝对路径中获取相对路径

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:使用 URI 类从两个绝对路径中获取相对路径

import java.io.File;
import java.net.URI;

public class Main {
  public static void main(String[] args) {

    try {

      // Two absolute paths
      File absolutePath1 = new File("C:\\Users\\Desktop\\gobeta\\Java\\Time.java");
      System.out.println("Absolute Path1: " + absolutePath1);
      File absolutePath2 = new File("C:\\Users\\Desktop");
      System.out.println("Absolute Path2: " + absolutePath2);

      // convert the absolute path to URI
      URI path1 = absolutePath1.toURI();
      URI path2 = absolutePath2.toURI();

      // create a relative path from the two paths
      URI relativePath = path2.relativize(path1);

      // convert the URI to string
      String path = relativePath.getPath();

      System.out.println("Relative Path: " + path);

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

输出

Absolute Path1: C:\Users\Desktop\gobeta\Java\Time.java
Absolute Path2: C:\Users\Desktop
Relative Path: gobeta/Java/Time.java

在上面的例子中,我们有两个名为 absolutePath1absolutePath2的绝对路径. 我们已经使用 URI 类将绝对路径转换为相对路径。

  • toURI() - 将 File 对象转换为Uri
  • relativize() - 通过将两个绝对路径相互比较来提取相对路径
  • getPath() - 将 Uri 转换为字符串

示例 2:使用 String 方法从两个绝对路径中获取相对路径

import java.io.File;

public class Main {
  public static void main(String[] args) {

    // Create file objects
    File file1 = new File("C:\\Users\\Desktop\\gobeta\\Java\\Time.java");
    File file2 = new File("C:\\Users\\Desktop");

    // convert file objects to string
    String absolutePath1 = file1.toString();
    System.out.println("Absolute Path1: " + absolutePath1);
    String absolutePath2 = file2.toString();
    System.out.println("Absolute Path2: " + absolutePath2);

    // get the relative path
    String relativePath = absolutePath1.substring(absolutePath2.length());
    System.out.println("Absolute Path: " + relativePath);
  }
}

输出

Absolute Path1: C:\Users\Desktop\Program\Java\Time.java
Absolute Path2: C:\Users\Desktop
Absolute Path: \Program\Java\Time.java

在上面的示例中,我们已将文件路径转换为字符串。注意这一行,

absolutePath1.substring(absolutePath2.length())

在这里,该 substring() 方法返回 absolutePath2 的从等于 absolutePath1 的长度的索引开始的部分. 也就是表示从 absolutePath1 中删除了 absolutePath2 之后剩下的的字符串.

示例 3:使用 java.nio.file 包从两个绝对路径中获取一个相对路径

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

public class Main {
  public static void main(String[] args) {

    // Create file objects
    Path absolutePath1 = Paths.get("C:\\Users\\Desktop\\gobeta\\Java\\Time.java");
    Path absolutePath2 = Paths.get("C:\\Users\\Desktop");

    // convert the absolute path to relative path
    Path relativePath = absolutePath2.relativize(absolutePath1);
    System.out.println("Relative Path: " + relativePath);

  }
}

输出

Relative Path: gobeta\Java\Time.java

在上面的例子中,我们已经使用了 Path 类的 relativize() 方法从两个绝对路径中获取了一个相对路径。

推荐读物