在 Java 中,文件是很常用的概念,这其中文件路径是一个很基础的内容,因为文件的创建,读取,写入和删除等操作都是依赖于文件路径的。但是你仔细看一下Java中 File
的 API 你会发现有这样三个方法返回路径。
了解这其中的差异,我们可以先看一看通用的路径的概念,即相对路径,绝对路径和规范路径。
.
用来代表当前的目录..
用来代表父目录/
为Linux/Mac等操作系统的路径分隔符\
为 Windows 路径分隔符:
为 Windows磁盘分割符,比如C:
当前目录
的路径有两个文件,路径为
/tmp/a/a.txt
/tmp/b/
那么 * 文件(a.txt
)相对当前目录(b
)的相对路径就是../a/a.txt
C:
或者D:
等/
假设C
盘下有temp
和temp1
两个目录
C:\temp
C:\temp1
那么这些都是指向同一个文件的绝对路径,且都是合法的。
C:\temp\test.txt
C:\temp\test.txt
C:\temp\TEST.TXT
C:\temp\.\test.txt
C:\temp1\..\temp\test.txt
备注: Windows下路径不区分大小写。
.
和..
等特殊字符举一个例子
一个相对路径为.././Java.txt
的文件,
/Users/androidyue/Documents/projects/PathSamples/.././Java.txt
/Users/androidyue/Documents/projects/Java.txt
备注:Canonical kə-ˈnä-ni-kəl
发音类似 可囊尼口
getPath
返回的路径可能是相对路径,也可能是绝对路径。getAbsolutePath
返回的路径是绝对路径getCanonicalPath
返回的路径是唯一的规范路径。import java.io.File;
public class PathDemo {
public static void main(String args[]) {
System.out.println("Path of the given file :");
File child = new File(".././Java.txt");
displayPath(child);
File parent = child.getParentFile();
System.out.println("Path of the parent folder :");
displayPath(parent);
File anotherFile = new File("a.txt");
System.out.println("Path of another file(a.txt)");
displayPath(anotherFile);
File anotherAbsFile = new File("/tmp/a.txt");
System.out.println("Path of another file(/tmp/a.txt)");
displayPath(anotherAbsFile);
}
public static void displayPath(File testFile) {
System.out.println("path : " + testFile.getPath());
System.out.println("absolute path : " + testFile.getAbsolutePath());
try {
System.out.println("canonical path : " + testFile.getCanonicalPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行后,输出的日志为
Path of the given file :
path : .././Java.txt
absolute path : /Users/androidyue/Documents/projects/PathSamples/.././Java.txt
canonical path : /Users/androidyue/Documents/projects/Java.txt
Path of the parent folder :
path : ../.
absolute path : /Users/androidyue/Documents/projects/PathSamples/../.
canonical path : /Users/androidyue/Documents/projects
Path of another file(a.txt)
path : a.txt
absolute path : /Users/androidyue/Documents/projects/PathSamples/a.txt
canonical path : /Users/androidyue/Documents/projects/PathSamples/a.txt
Path of another file(/tmp/a.txt)
path : /tmp/a.txt
absolute path : /tmp/a.txt
canonical path : /private/tmp/a.txt
Process finished with exit code 0
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有