温馨提示×

Java getAbsolutePath()获取绝对路径和相对路径

小云
156
2023-09-23 06:10:34
栏目: 编程语言

Java中的File类的getAbsolutePath()方法用于获取文件的绝对路径。该方法返回一个字符串,表示文件的绝对路径。绝对路径是指从文件系统的根目录开始的完整路径。

以下是一个使用getAbsolutePath()方法获取绝对路径的示例:

import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("example.txt");
String absolutePath = file.getAbsolutePath();
System.out.println("绝对路径: " + absolutePath);
}
}

输出结果将会是类似于以下内容的绝对路径:

绝对路径: C:\path\to\example.txt

相对路径是指相对于当前工作目录的路径。可以通过System.getProperty(“user.dir”)方法获取当前工作目录。然后将相对路径与当前工作目录拼接起来,即可得到文件的绝对路径。

以下是一个使用相对路径和当前工作目录获取绝对路径的示例:

import java.io.File;
public class Main {
public static void main(String[] args) {
String relativePath = "example.txt";
String currentDirectory = System.getProperty("user.dir");
String absolutePath = currentDirectory + File.separator + relativePath;
System.out.println("绝对路径: " + absolutePath);
}
}

输出结果将会是类似于以下内容的绝对路径:

绝对路径: C:\path\to\current\directory\example.txt

0