English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à obtenir un chemin relatif à partir de deux chemins absolus en utilisant les méthodes String, la classe URI et le paquet java.nio.file de Java.
import java.io.File; import java.net.URI; class Main {}} public static void main(String[] args) { try { //Deux chemins absolus File absolutePath1 = new File("C:\\Users\\Desktop\\w3codebox\Java\Time.java"); System.out.println("绝对路径1: " + absolutePath1); File absolutePath2 = new File("C:\\Users\\Desktop"); System.out.println("绝对路径2: " + absolutePath2); //Convertir un chemin absolu en URI URI path1 = absolutePath1.toURI(); URI path2 = absolutePath2.toURI(); //Créer un chemin relatif à partir de deux chemins URI relativePath = path2.relativize(path)1); //将URI转换为字符串 String path = relativePath.getPath(); System.out.println("Relative path: " + path); } catch (Exception e) { e.getStackTrace(); } } }
Output result
绝对路径1: C:\Users\Desktop\w3codebox\Java\Time.java 绝对路径2: C:\Users\Desktop Relative path: w3codebox/Java/Time.java
在上面的示例中,我们有两个名为 absolutePath1 和 absolutePath2 的绝对路径。我们已经使用URI类将绝对路径转换为相对路径。
toURI() - 将File对象转换为Uri
relativize() - 通过将两个绝对路径相互比较来提取相对路径
getPath() - 将URI转换为字符串
import java.io.File; class Main {}} public static void main(String[] args) { //Create file object File file1 = new File("C:\\Users\\Desktop\\w3codebox\Java\Time.java"); File file2 = new File("C:\\Users\\Desktop"); // 将文件对象转换为字符串 String absolutePath1 = file1.toString(); System.out.println("绝对路径1: " + absolutePath1); String absolutePath2 = file2.toString(); System.out.println("绝对路径2: " + absolutePath2); //获取相对路径 String relativePath = absolutePath1.substring(absolutePath2.length()); System.out.println("绝对路径: " + relativePath); } }
Output result
绝对路径1: C:\Users\Desktop\w3codebox\Java\Time.java 绝对路径2: C:\Users\Desktop 绝对路径: \w3codebox\Java\Time.java
在上面的示例中,我们将文件路径转换为字符串。注意表达式
absolutePath1.substring(absolutePath2.length())
这里,substring ()方法返回 absolutePath1的一部分,从索引等于 absolutePath2的长度开始。也就是说,从 absolutePath1中删除 absolutePath2 表示的字符串。
要了解有关子字符串如何工作的更多信息,请访问Java String substring()。
import java.nio.file.Path; import java.nio.file.Paths; class Main {}} public static void main(String[] args) { //Create file object Path absolutePath1 = Paths.get("C:\\Users\\Desktop\\w3codebox\Java\Time.java"); Path absolutePath2 = Paths.get("C:\\Users\\Desktop"); //Convert absolute path to relative path Path relativePath = absolutePath2.relativize(absolutePath1); System.out.println("Relative path: " + relativePath); } }
Output result
Relative path: w3codebox\Java\Time.java
In the above example, we used the relativize() method of the Path interface to obtain the relative path from two absolute paths.