java獲取當前路徑[轉]

java 獲取當前路徑

http://hi.baidu.com/hbmubai/blog/item/0a6baff3f1b3a255352accc2.html 2008-05

 

1 、利用 System.getProperty() 函數獲取當前路徑:

System.out.println(System.getProperty("user.dir"));//user.dir 指定了當前的路徑

 

2 、使用 File 提供的函數獲取當前路徑:

File directory = new File("");// 設定爲當前文件夾

try{

    System.out.println(directory.getCanonicalPath());// 獲取標準的路徑

    System.out.println(directory.getAbsolutePath());// 獲取絕對路徑

}catch(Exceptin e){}

 

File.getCanonicalPath() File.getAbsolutePath() 大約只是對於 new File(".") new File("..") 兩種路徑有所區別。

 

# 對於 getCanonicalPath() 函數,“ ." 就表示當前的文件夾,而” .. “則表示當前文件夾的上一級文件夾

# 對於 getAbsolutePath() 函數,則不管” . ”、“ .. ”,返回當前的路徑加上你在 new File() 時設定的路徑

# 至於 getPath() 函數,得到的只是你在 new File() 時設定的路徑

 

比如當前的路徑爲 C:\test

File directory = new File("abc");

directory.getCanonicalPath(); // 得到的是 C:\test\abc

directory.getAbsolutePath();    // 得到的是 C:\test\abc

direcotry.getPath();                    // 得到的是 abc

 

File directory = new File(".");

directory.getCanonicalPath(); // 得到的是 C:\test

directory.getAbsolutePath();    // 得到的是 C:\test\.

direcotry.getPath();                    // 得到的是 .

 

File directory = new File("..");

directory.getCanonicalPath(); // 得到的是 C:\

directory.getAbsolutePath();    // 得到的是 C:\test\..

direcotry.getPath();                    // 得到的是 ..

 

關於System.getProperty方法的參數見

System.getProperty方法的參數大全

 

 

 

 

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