欢迎光临
我们一直在努力

getPath和 getAbsolutePath的区别


版权声明

  • 本文原创作者:谷哥的小弟
  • 作者博客地址:http://blog.csdn.net/lfdfhl

在这里插入图片描述

在 Java 中,File 类用于表示文件或目录路径。创建 File 对象时,可以使用相对路径,也可以使用绝对路径。getPath() 和 getAbsolutePath() 都可以获取路径字符串,但二者返回的内容并不完全相同。

getPath()方法

getPath() 方法用于返回创建 File 对象时传入的路径字符串。

如果创建 File 对象时使用的是相对路径,getPath() 返回相对路径;如果使用的是绝对路径,getPath() 返回绝对路径。

示例代码如下:

import java.io.File;

public class FilePathDemo {
public static void main(String[] args) {
File file = new File("test.txt");

System.out.println(file.getPath());
}
}

在该示例中,new File("test.txt") 使用的是相对路径,因此 getPath() 的输出结果通常为:

test.txt

getAbsolutePath()方法

getAbsolutePath() 方法用于返回文件或目录的绝对路径。

如果创建 File 对象时使用的是相对路径,getAbsolutePath() 会根据当前程序的运行目录,将相对路径转换为绝对路径。

示例代码如下:

import java.io.File;

public class FileAbsolutePathDemo {
public static void main(String[] args) {
File file = new File("test.txt");

System.out.println(file.getAbsolutePath());
}
}

假设当前程序的运行目录是:

D:\\java-demo

那么 getAbsolutePath() 的输出结果可能为:

D:\\java-demo\\test.txt

两者对比示例

下面通过同一个 File 对象对两个方法进行比较:

import java.io.File;

public class FilePathCompareDemo {
public static void main(String[] args) {
File file = new File("test.txt");

System.out.println("getPath(): " + file.getPath());
System.out.println("getAbsolutePath(): " + file.getAbsolutePath());
System.out.println("user.dir: " + System.getProperty("user.dir"));
}
}

可能的输出结果如下:

getPath(): test.txt
getAbsolutePath(): D:\\java-demo\\test.txt
user.dir: D:\\java-demo

在该示例中,getPath() 返回的是创建 File 对象时传入的路径;getAbsolutePath() 返回的是根据当前程序运行目录转换后的绝对路径。System.getProperty("user.dir") 表示当前程序的运行目录,相对路径转换为绝对路径时通常会以它作为参考。

总结

getPath() 返回的是创建 File 对象时使用的路径字符串,路径形式取决于创建对象时传入的内容。

getAbsolutePath() 返回的是绝对路径。如果原路径是相对路径,它会结合当前程序运行目录生成完整路径。

因此,可以简单理解为:

getPath():看传入什么,就返回什么形式的路径。
getAbsolutePath():返回完整的绝对路径。

赞(0)
未经允许不得转载:171主机测评 » getPath和 getAbsolutePath的区别
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址