java中獲得當前文件路徑多種方法
public String getClassPath(){
String path="";
try {
path=new File(getClass().getClassLoader().getResource("").toURI()).getPath();
}catch (URISyntaxException ex) {}
return path;
}
String path="";
try {
path=new File(getClass().getClassLoader().getResource("").toURI()).getPath();
}catch (URISyntaxException ex) {}
return path;
}
取程序運行時的目錄路徑。即程序在那里雙擊或BAT文件所在的路徑
System.getProperties("user.dir");
第一種:
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
System.out.println(f);
結果:
C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebin
獲取當前類的所在工程路徑;
如果不加“/”
File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);
System.out.println(f);
結果:
C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebincomtest
獲取當前類的絕對路徑;
第二種:
File directory = new File("");//參數(shù)為空
String courseFile = directory.getCanonicalPath() ;
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
結果:
C:Documents and SettingsAdministratorworkspaceprojectName
獲取當前類的所在工程路徑;
第三種:
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");
System.out.println(xmlpath);
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等內(nèi)容,請參考RFC相關文檔標準。RFC 2396: Uniform Resource Identifiers
(URI): Generic Syntax
[以上摘自:http://www.111cn.net/jsp/Java/39141.htm]
它們的區(qū)別如下:
package:當你在建立一個package時,它自動建立到source folder下,也只能建立在這個目錄之下.
source folder:存放java源代碼的文件夾,當然也包括一些package文件夾,還可以包含其他文件.
項目構建后,source folder里面的java自動編譯成class文件到相應的bin文件夾中,其他文件也會移到到相應的目錄下.
folder:里面可以放入任何文件.包括java源文件,jar文件,其他文件(例如,圖片,聲音等).在此我說明一下,如果里面含有java源文件,不管程序是否正確,eclipse都不會報錯,把它們當做普通文件處理.但是項目如果要使用這里面的文件,情況就不同了.
以上摘自csdn論壇某大神的解釋,深表贊同。
此外,一旦你將某個路徑(比如配置文件路徑:src/configrations)設置為source folder,那么,需要引用到configurations下配置文件的其他地方在引用文件時就不能寫全路徑(如:“/configurations/XXX.properties”),而應該直接寫“/XXX.properties”。