java中File類的getPath(),getAbsolutePath(),getCanonicalPath()區別

1. getPath()得到的文件構造時參數中給出的路徑

File file = new File(".\\hello.txt");

System.out.println(file.getPath());

輸出的路徑爲 .\hello.txt

File file = new File("E:\\workspace\\java\\hello.txt");

System.out.println(file.getPath());

輸出的路徑爲 E:\\workspace\\java\\hello.txt

2. getAbsolutePath()返回的是文件的絕地路徑。

File file = new File(".\\hello.txt");

System.out.println(file.getAbsolutePath());

輸出的路徑爲 E:\workspace\java\\hello.txt

File file = new File("E:\\workspace\\java\\hello.txt");

System.out.println(file.getAbsolutePath());

輸出的路徑爲 E:\workspace\java\hello.txt

3. getCanonicalPath()也是返回文件的絕對路徑,但會去除[..]這樣的符號,即返回的是標準的絕地路徑。

File file = new File("..\\java\\hello.txt");

System.out.println(file.getAbsolutePath());

System.out.println(file.getCanonicalPath());

getAbsolutePath()輸出的路徑爲 E:\workspace\..\java\hello.txt

getCanonicalPath()輸出的路徑爲 E:\workspace\java\hello.txt

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章