File類提供了getPath()、getAbsolutePath()、getCanonicalPath()三個方法來提供檔案路徑,本文将通過下面的執行個體示範它們的差別與聯系:
public class FileTest {
static void printPath(String path){
System.out.println("輸入:" + path);
File file = new File(path);
printPath(file);
}
static void printPath(File file){
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
System.err.println("Error occurs when invoking getCanonicalPath()");
}
System.out.println();
}
public static void main(String[] args) {
printPath("C:\\Users\\qwer\\Desktop\\osu\\圖解HTTP.pdf");
printPath("圖解HTTP.pdf");
printPath(".\\圖解HTTP.pdf");
printPath("..\\不存在的目錄\\圖解HTTP.pdf");
}
}
結果為:
輸入:C:\Users\qwer\Desktop\osu\圖解HTTP.pdf
C:\Users\qwer\Desktop\osu\圖解HTTP.pdf
C:\Users\qwer\Desktop\osu\圖解HTTP.pdf
C:\Users\qwer\Desktop\osu\圖解HTTP.pdf
輸入:圖解HTTP.pdf
圖解HTTP.pdf
D:\eclipsepreferences\Tests\圖解HTTP.pdf
D:\eclipsepreferences\Tests\圖解HTTP.pdf
輸入:.\圖解HTTP.pdf
.\圖解HTTP.pdf
D:\eclipsepreferences\Tests\.\圖解HTTP.pdf
D:\eclipsepreferences\Tests\圖解HTTP.pdf
輸入:..\不存在的目錄\圖解HTTP.pdf
..\不存在的目錄\圖解HTTP.pdf
D:\eclipsepreferences\Tests\..\不存在的目錄\圖解HTTP.pdf
D:\eclipsepreferences\不存在的目錄\圖解HTTP.pdf
用于測試的路徑中,第一個是絕對路徑,後三個都是相對路徑。從輸出結果中,可以得出幾點結論:
(1)對于絕對路徑,三種方法的輸出結果相同。
(2)對于相對路徑,getPath()不做任何處理,輸出路徑等于輸入路徑;getAbsolutePath()簡單地将目前工作目錄(即項目檔案夾路徑,本文中為D:\eclipsepreferences\Tests\)與輸入的相對路徑拼接在一起,包括.\與..\;getCanonicalPath()會在getAbsolutePath()的基礎上解析出完整的路徑。
(3)Java中,相對路徑的根預設在項目檔案夾路徑。
(4)getCanonicalPath()傳回的必定是絕對路徑。