java中得到當前文件路徑多種方法java
public String getClassPath(){ String path=""; try { path=new File(getClass().getClassLoader().getResource("").toURI()).getPath(); }catch (URISyntaxException ex) {} return path; }jsp
取程序運行時的目錄路徑。即程序在那裏雙擊或BAT文件所在的路徑 System.getProperties("user.dir");this
第一種: File f = new File(this.getClass().getResource("/").getPath()); System.out.println(f);spa
結果: C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebin.net
獲取當前類的所在工程路徑; 若是不加「/」 File f = new File(this.getClass().getResource("").getPath()); System.out.println(f);orm
結果: C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebincomtestxml
獲取當前類的絕對路徑;htm
第二種: File directory = new File("");//參數爲空 String courseFile = directory.getCanonicalPath() ;文檔
System.out.println(courseFile); 結果: C:Documents and SettingsAdministratorworkspaceprojectNameget
獲取當前類的所在工程路徑;
第三種: URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt"); System.out.println(xmlpath);
結果: file:/C:/Documents%20and% 20Settings/Administrator/workspace/projectName/bin/selected.txt
獲取當前工程src目錄下selected.txt文件的路徑
第四種: System.out.println(System.getProperty("user.dir"));
結果: C:Documents and SettingsAdministratorworkspaceprojectName
獲取當前工程路徑
第五種: System.out.println( System.getProperty("java.class.path"));
結果: C:Documents and SettingsAdministratorworkspaceprojectNamebin
獲取當前工程路徑
絕對路徑和相對路徑: 絕對路徑就是你的主頁上的文件或目錄在硬盤上真正的路徑,(URL和物理路徑)例如:C:xyz
est.txt 表明了test.txt文件的絕對路徑。http://www.111cn.net 也表明了一個URL絕對
路徑。相對路徑:相對與某個基準目錄的路徑。包含Web的相對路徑(HTML中的相對目錄)
,例如:在Servlet中,"/"表明Web應用的跟目錄。和物理路徑的相對錶示。例如:"./" 代
表當前目錄,"../"表明上級目錄。這種相似的表示,也是屬於相對路徑。另外關於URI,
URL,URN等內容,請參考RFC相關文檔標準。RFC 2396: Uniform Resource Identifiers
(URI): Generic Syntax [以上摘自:http://www.111cn.net/jsp/Java/39141.htm]