java 獲取根路勁

來自網(wǎng)絡(luò),侵刪。

一 相對路徑的獲得
說明:相對路徑(即不寫明時候到底相對誰)均可通過以下方式獲得(不論是一般的java項目還是web項目)

String relativelyPath=System.getProperty("user.dir"); 

上述相對路徑中,java項目中的文件是相對于項目的根目錄
web項目中的文件路徑視不同的web服務(wù)器不同而不同(tomcat是相對于 tomcat安裝目錄\bin)

二 類加載目錄的獲得(即當(dāng)運行時某一類時獲得其裝載目錄)
1.1)通用的方法一(不論是一般的java項目還是web項目,先定位到能看到包路徑的第一級目錄)

InputStream is=TestAction.class.getClassLoader().getResourceAsStream("test.txt"); 

(test.txt文件的路徑為 項目名\src\test.txt;類TestAction所在包的第一級目錄位于src目錄下)

上式中將TestAction,test.txt替換成對應(yīng)成相應(yīng)的類名和文件名字即可

1.2)通用方法二 (此方法和1.1中的方法類似,不同的是此方法必須以'/'開頭,參考http://riddickbryant.iteye.com/blog/436693)

InputStream is=Test1.class.getResourceAsStream("/test.txt"); 

(test.txt文件的路徑為 項目名\src\test.txt,類Test1所在包的第一級目錄位于src目錄下)

三 web項目根目錄的獲得(發(fā)布之后)
1 從servlet出發(fā)

可建立一個servlet在其的init方法中寫入如下語句

ServletContext s1=this.getServletContext();
String temp=s1.getRealPath("/"); (關(guān)鍵) 

結(jié)果形如:D:\工具\Tomcat-6.0\webapps\002_ext\ (002_ext為項目名字)

如果是調(diào)用了s1.getRealPath("")則輸出D:\工具\Tomcat-6.0\webapps\002_ext(少了一個"")

2 從httpServletRequest出發(fā)

String cp11111=request.getSession().getServletContext().getRealPath("/");

結(jié)果形如:D:\工具\Tomcat-6.0\webapps\002_ext\

四 classpath的獲取(在Eclipse中為獲得src或者classes目錄的路徑)

方法一
Thread.currentThread().getContextClassLoader().getResource("").getPath()

eg: String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("t---"+t);

輸出:t---/E:/order/002_ext/WebRoot/WEB-INF/classes/

方法二 
JdomParse.class.getClassLoader().getResource("").getPath() (JdomParse為src某一個包中的類,下同)

eg:String p1=JdomParse.class.getClassLoader().getResource("").getPath();
System.out.println("JdomParse.class.getClassLoader().getResource--"+p1);

輸出: JdomParse.class.getClassLoader().getResource--/E:/order/002_ext/WebRoot/WEB-INF/classes/

另外,如果想把文件放在某一包中,則可以 通過以下方式獲得到文件(先定位到該包的最后一級目錄)

eg String p2=JdomParse.class.getResource("").getPath(); 
System.out.println("JdomParse.class.getResource---"+p2);

輸出: JdomParse.class.getResource---/E:/order/002_ext/WebRoot/WEB-INF/classes/jdom/ (JdomParse為src目錄下jdom包中的類)

四 屬性文件的讀取:

方法 一

InputStream in = lnew BufferedInputStream( new FileInputStream(name));    
Properties p = new Properties();   
p.load(in);

注意路徑的問題,做執(zhí)行之后就可以調(diào)用p.getProperty("name")得到對應(yīng)屬性的值

方法二

Locale locale = Locale.getDefault(); 
ResourceBundle localResource = ResourceBundle.getBundle("test/propertiesTest", locale); 
String value = localResource.getString("test"); 
System.out.println("ResourceBundle: " + value);

工程src目錄下propertiesTest.properties(名字后綴必須為properties)文件內(nèi)容如下:

test=hello word

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容