File file = new File(".\\src\\test.txt");
1、getPath():
返回定義時的路徑,(就是你寫什么路徑,他就返回什么路徑)
2、getAbsolutePath():
返回絕對路徑,但不會處理“.”和“..”的情況
3、getCanonicalPath():
返回的是規(guī)范化的絕對路徑,相當于將getAbsolutePath()中的“.”和“..”解析成對應的正確的路徑
例一(使用:“.\”一個點路徑)
//文件本地路徑: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());
//輸出結果:
.\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");
//輸出結果:
..\84695\Desktop\其他\test.docx
E:\HX-projects\hh\..\84695\Desktop\其他\test.docx
E:\HX-projects\84695\Desktop\其他\test.docx (注意這個結果的路徑,與一個點時不一樣;因為他解析了“.”和“..”的情況。)
例三(使用文件絕對路徑)
//文件本地路徑:C:\Users\84695\Desktop\其他\test.docx
File file = new File("C:\\Users\\84695\\Desktop\\其他\\test.docx");
//輸出結果:
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx
C:\Users\84695\Desktop\其他\test.docx
"./"和"../"的區(qū)別
/ :表示當前路徑的根路徑
./ :表示當前路徑
../ :表示父級路徑,當前路徑所在的上一級路徑