| 方法 | 说明 |
|---|---|
| getPath | 以构造路径作为返回值 |
| getAbsolutePath | 以当前路径+构造路径作为返回值 |
| getCanonicalPath | 以全路径作为返回值(如果构造路径包含.或…,会进行处理) |
需要理解一下Canonical单词含义

测试示例
public static void main(String[] args) throws IOException {
File file1 = new File("./hello.txt");
File file2 = new File("/Users/caowei/hello.txt");
System.out.println("-----默认相对路径:取得路径不同------");
System.out.println(file1.getPath());
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getCanonicalPath());
System.out.println("-----默认绝对路径:取得路径相同------");
System.out.println(file2.getPath());
System.out.println(file2.getAbsolutePath());
System.out.println(file2.getCanonicalPath());
SpringApplication.run(Demo4Application.class, args);
}
结果如下
-----默认相对路径:取得路径不同------
./hello.txt
/Users/caowei/workspace/gitee/demo4/./hello.txt
/Users/caowei/workspace/gitee/demo4/hello.txt
-----默认绝对路径:取得路径相同------
/Users/caowei/hello.txt
/Users/caowei/hello.txt
/Users/caowei/hello.txt
本文介绍了Java中File类的三个核心方法:getPath、getAbsolutePath和getCanonicalPath,用于获取文件路径的不同形式。通过示例代码展示了它们的区别,如getPath返回构造路径,getAbsolutePath返回当前路径与构造路径的组合,而getCanonicalPath则处理了相对路径中的.和...等问题,返回规范化的全路径。
995

被折叠的 条评论
为什么被折叠?



