1. 程式人生 > >getCanonicalpath函式的簡單學習

getCanonicalpath函式的簡單學習

今天學習newsgroup文件預處理的java實現時,遇到了getCanonicalpath()函式,之前沒接觸過,所以查了下資料,整理如下。

getCononicalPath()是獲取文件路徑的一個函式,與常用的getPath(),getAbsolutePath()有所區別。

1. getPath()得到的檔案構造時引數中給出的路徑。

例如:    

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

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

輸出的路徑為 .\test.txt。

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

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

 輸出的路徑為 E:\\workspace\\java\\test.txt。


2. getAbsolutePath()返回的是檔案的絕地路徑。


例如:    

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

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

輸出的路徑為 E:\workspace\java\\est.txt。

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

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

輸出的路徑為 E:\workspace\java\test.txt。


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

例如:

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

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

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

getAbsolutePath()輸出的路徑為 E:\workspace\..\java\test.txt。

getCanonicalPath()輸出的路徑為 E:\workspace\java\test.txt。