很多時(shí)候我們不應(yīng)該把一些會(huì)經(jīng)常變動(dòng)的數(shù)據(jù)直接寫在代碼中;這樣會(huì)造成以后維護(hù)很不方便.每次有改動(dòng)還需要重新編譯源代碼,這時(shí)候我們可以考慮可以把這些數(shù)據(jù)插入數(shù)據(jù)庫或者寫在一個(gè)配置文件中;如果數(shù)據(jù)量不大;我們直接把這些文件寫在配置文件中是一個(gè)不錯(cuò)的選擇,下面我們就來看看使用java來讀取properties配置文件的過程:
首先我們應(yīng)該建立一個(gè).properties配置文件;properties配置文件都是一個(gè)一對一的鍵值對;比如:
userName=zhangsan password=123456 #age=23 如果在前面加上#代表該鍵值對被注釋掉
Properties dataproperties = new Properties(); String datapath="%projecthome%\\WebRoot\\WEB-INF\\db.properties";//這個(gè)是db.properties文件所在的路徑 dataproperties.load(new FileInputStream(datapath)); String url = dataproperties.getProperty("db.url").toString(); String name = dataproperties.getProperty("db.name").toString(); String pass = dataproperties.getProperty("db.pass").toString();
System.out.println("db.url is:"+url); System.out.println("db.name is:"+name); System.out.println("db.pass is:"+pass); //打印出: //db.url is:jdbc:mysql://127.0.0.1:3306/dbname //db.name is:root //db.pass is:root 通過以上代碼就實(shí)現(xiàn)了使用java來讀取properties配置文件!
本文來自: 114JAVA技術(shù)網(wǎng)(www.) 詳細(xì)出處參考:http://www./javajichu/201005/1181.html
|