
2014年4月19日
java中獲得當(dāng)前文件路徑多種方法
public String getClassPath(){
String path="";
try {
path=new File(getClass().getClassLoader().getResource("").toURI()).getPath();
}catch (URISyntaxException ex) {}
return path;
}
取程序運(yùn)行時(shí)的目錄路徑。即程序在那里雙擊或BAT文件所在的路徑
System.getProperties("user.dir");
第一種:
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
結(jié)果:
C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebin
獲取當(dāng)前類的所在工程路徑;
如果不加“/”
File f = new File(this.getClass().getResource("").getPath());
System.out.println(f);
結(jié)果:
C:Documents%20and%20SettingsAdministratorworkspaceprojectNamebincomtest
獲取當(dāng)前類的絕對(duì)路徑;
第二種:
File directory = new File("");//參數(shù)為空
String courseFile = directory.getCanonicalPath() ;
System.out.println(courseFile);
結(jié)果:
C:Documents and SettingsAdministratorworkspaceprojectName
獲取當(dāng)前類的所在工程路徑;
第三種:
URL xmlpath = this.getClass().getClassLoader().getResource("selected.txt");
System.out.println(xmlpath);
結(jié)果:
file:/C:/Documents%20and%
20Settings/Administrator/workspace/projectName/bin/selected.txt
獲取當(dāng)前工程src目錄下selected.txt文件的路徑
第四種:
System.out.println(System.getProperty("user.dir"));
結(jié)果:
C:Documents and SettingsAdministratorworkspaceprojectName
獲取當(dāng)前工程路徑
第五種:
System.out.println( System.getProperty("java.class.path"));
結(jié)果:
C:Documents and SettingsAdministratorworkspaceprojectNamebin
獲取當(dāng)前工程路徑
絕對(duì)路徑和相對(duì)路徑:
絕對(duì)路徑就是你的主頁(yè)上的文件或目錄在硬盤(pán)上真正的路徑,(URL和物理路徑)例如:C:xyz
est.txt 代表了test.txt文件的絕對(duì)路徑。http://www.111cn.net 也代表了一個(gè)URL絕對(duì)
路徑。相對(duì)路徑:相對(duì)與某個(gè)基準(zhǔn)目錄的路徑。包含Web的相對(duì)路徑(HTML中的相對(duì)目錄)
,例如:在Servlet中,"/"代表Web應(yīng)用的跟目錄。和物理路徑的相對(duì)表示。例如:"./" 代
表當(dāng)前目錄,"../"代表上級(jí)目錄。這種類似的表示,也是屬于相對(duì)路徑。另外關(guān)于URI,
URL,URN等內(nèi)容,請(qǐng)參考RFC相關(guān)文檔標(biāo)準(zhǔn)。RFC 2396: Uniform Resource Identifiers
(URI): Generic Syntax
[以上摘自:http://www.111cn.net/jsp/Java/39141.htm]
posted @
2014-04-19 15:32 黑客的蝸牛 閱讀(10861) |
評(píng)論 (0) |
編輯 收藏