在java web開(kāi)發(fā)的時(shí)候經(jīng)常會(huì)用到讀取讀取或存放文件,這個(gè)文件的默認(rèn)路徑在哪里呢?寫(xiě)死在程序里面顯然是可以的,但這樣子不利于位于,假如有一天項(xiàng)目從window移植到linux,或者保存文件的路徑變了,就需要去源代碼中查找,進(jìn)行替換,這樣子不僅效率低,而且程序的耦合度也會(huì)過(guò)高,這里我用了一個(gè)properties文件用于存放文件的保存路徑,需要保存或者讀取都來(lái)自己properties所保存的路徑。
1、我存放的propeities文件路徑
因?yàn)閘inux和window上面的分盤(pán)是不一樣的,所以我把保存文件路徑的properties文件放在項(xiàng)目中,所以可以通過(guò)獲取tomcat所以路徑來(lái)獲取該文件
2、properties文件內(nèi)容
這里文件路徑我使用了 / ,可以兼容linux系統(tǒng)和window,假如在程序中文件的分隔符建議使用File.separator作為分隔符,以兼容不同的操作系統(tǒng)。
filePath=E:/file
3、獲取文件所在的路徑
1
2
3
4
5
6
|
String dir = System.getProperty( "user.dir" ); //獲得tomcat所在的工作路徑 System.out.println(dir); //獲取到存儲(chǔ)了文件存儲(chǔ)位置的filedir.properties 文件路徑 String dir2 = dir.substring( 0 , dir.length()- 4 ) + File.separator + "webapps" + File.separator + "NGBOSSmonitor" +File.separator + "WEB-INF" + File.separator + "classes" + File.separator + "META-INF" + File.separator + "config" + File.separator + "filedir.properties" ; |
dir 獲取到的是 :D:\Tocat\tomcat6.0.37\bin
我獲取的dir2 為 D:\Tocat\tomcat6.0.37\webapps\你的項(xiàng)目名\WEB-INF\classes\META-INF\config\filedir.properties
4、通過(guò)properties文件,獲取到里面的filePath的值,即獲得 E:/file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
/** * 獲取filePath路徑【properities文件】中key對(duì)應(yīng)的值, * @param filePath properities文件路徑【包含properities文件】 * @param key 要查找的key值 * @return key對(duì)應(yīng)的value */ public String GetValueByKey(String filePath, String key) { Properties pps = new Properties(); try { InputStream in = new BufferedInputStream ( new FileInputStream(filePath)); pps.load(in); String value = pps.getProperty(key); //System.out.println(key + " = " + value); in.close(); return value; } catch (IOException e) { e.printStackTrace(); return null ; } } |
到達(dá)這里,已經(jīng)完整得獲得了filedir.properties 里面得 filePath的值。
5、總結(jié)
開(kāi)發(fā)過(guò)程中,使程序解耦合很重要,耦合程度越低,我們開(kāi)發(fā)修改越容易。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。