File file = new File(".\\src\\test.txt");
1、getPath():
返回定義時的路徑仙蛉,(就是你寫什么路徑笋敞,他就返回什么路徑)
2、getAbsolutePath():
返回絕對路徑捅儒,但不會處理“.”
和“..”
的情況
3液样、getCanonicalPath():
返回的是規(guī)范化的絕對路徑振亮,相當(dāng)于將getAbsolutePath()
中的“.”
和“..”
解析成對應(yīng)的正確的路徑
例一(使用:“.\”一個點路徑)
//文件本地路徑:C:\Users\84695\Desktop\其他\test.docx
File file = new File(".\\84695\\Desktop\\其他\\test.docx");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
//輸出結(jié)果:
.\84695\Desktop\其他\test.docx
E:\HX-projects\hh\.\84695\Desktop\其他\test.docx
E:\HX-projects\hh\84695\Desktop\其他\test.docx (項目路徑:E:\HX-projects\hh)
例二(使用:“..\”兩個點路徑)
//文件本地路徑:C:\Users\84695\Desktop\其他\test.docx
File file = new File("..\\84695\\Desktop\\其他\\test.docx");
//輸出結(jié)果:
..\84695\Desktop\其他\test.docx
E:\HX-projects\hh\..\84695\Desktop\其他\test.docx
E:\HX-projects\84695\Desktop\其他\test.docx (注意這個結(jié)果的路徑巧还,與一個點時不一樣鞭莽;因為他解析了“.”和“..”的情況。)
例三(使用文件絕對路徑)
//文件本地路徑:C:\Users\84695\Desktop\其他\test.docx
File file = new File("C:\\Users\\84695\\Desktop\\其他\\test.docx");
//輸出結(jié)果:
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx
"./"
和"../"
的區(qū)別
/ :表示當(dāng)前路徑的根路徑
./ :表示當(dāng)前路徑
../ :表示父級路徑麸祷,當(dāng)前路徑所在的上一級路徑