方式一:采用servletcontext讀取
獲取配置文件的realpath,然后通過文件流讀取出來或者通過方法getreasurceasstream()。
因為是用servletcontext讀取文件路徑,所以配置文件可以放入在web-inf的classes目錄中,也可以在應(yīng)用層級及web-inf的目錄中。文件存放位置具體在eclipse工程中的表現(xiàn)是:可以放在src下面,也可放在web-inf及web-root下面等。因為是讀取出路徑后,用文件流進(jìn)行讀取的,所以可以讀取任意的配置文件包括xml和properties。缺點(diǎn):不能在servlet外面應(yīng)用讀取配置信息。
1.首先創(chuàng)建一個動態(tài)的javaweb項目,項目目錄如下:
2.創(chuàng)建一個servlet(filereader.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
package com.xia.filereader; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.text.messageformat; import java.util.properties; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; public class filereader extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { /** * response.setcontenttype("text/html;charset=utf-8");目的是控制瀏覽器用utf-8進(jìn)行解碼; * 這樣就不會出現(xiàn)中文亂碼了 */ response.setheader( "content-type" , "text/html;charset=utf-8" ); readsrcdirpropcfgfile(response); //讀取src目錄下的db1.properties配置文件 response.getwriter().println( "<hr/>" ); readwebrootdirpropcfgfile(response); //讀取webroot目錄下的db2.properties配置文件 response.getwriter().println( "<hr/>" ); readsrcsourcepackpropcfgfile(response); //讀取src目錄下的config目錄中的db3.properties配置文件 response.getwriter().println( "<hr/>" ); readwebinfpropcfgfile(response); //讀取web-inf目錄下的jdbc目錄中的db4.properties配置文件 } public void readsrcdirpropcfgfile(httpservletresponse response) throws ioexception { string path = "/web-inf/classes/db1.properties" ; inputstream in = this .getservletcontext().getresourceasstream(path); properties props = new properties(); props.load(in); string driver = props.getproperty( "jdbc.driver" ); string url = props.getproperty( "jdbc.url" ); string username = props.getproperty( "jdbc.username" ); string password = props.getproperty( "jdbc.password" ); response.getwriter().println( "讀取src目錄下的db1.properties配置文件" ); response.getwriter().println(messageformat.format( "driver={0},url={1},username={2},password={3}" , driver,url, username, password)); } public void readwebrootdirpropcfgfile(httpservletresponse response) throws ioexception{ string path = "/db2.properties" ; inputstream in = this .getservletcontext().getresourceasstream(path); properties props = new properties(); props.load(in); string driver = props.getproperty( "jdbc.driver" ); string url = props.getproperty( "jdbc.url" ); string username = props.getproperty( "jdbc.username" ); string password = props.getproperty( "jdbc.password" ); response.getwriter().println( "讀取webroot目錄下的db2.properties配置文件" ); response.getwriter().println(messageformat.format( "driver={0},url={1},username={2},password={3}" , driver,url, username, password)); } public void readsrcsourcepackpropcfgfile(httpservletresponse response) throws ioexception { string path = "/web-inf/classes/config/db3.properties" ; string realpath = this .getservletcontext().getrealpath(path); inputstreamreader reader = new inputstreamreader( new fileinputstream(realpath), "utf-8" ); properties props = new properties(); props.load(reader); string driver = props.getproperty( "jdbc.driver" ); string url = props.getproperty( "jdbc.url" ); string username = props.getproperty( "jdbc.username" ); string password = props.getproperty( "jdbc.password" ); response.getwriter().println( "讀取src目錄下的config目錄中的db3.properties配置文件" ); response.getwriter().println(messageformat.format( "driver={0},url={1},username={2},password={3}" , driver,url, username, password)); } public void readwebinfpropcfgfile(httpservletresponse response) throws ioexception { string path = "/web-inf/jdbc/db4.properties" ; string realpath = this .getservletcontext().getrealpath(path); system.out.println( "realpath:" +realpath); system.out.println( "contextpath:" + this .getservletcontext().getcontextpath()); inputstreamreader reader = new inputstreamreader( new fileinputstream(realpath), "utf-8" ); properties props = new properties(); props.load(reader); string driver = props.getproperty( "jdbc.driver" ); string url = props.getproperty( "jdbc.url" ); string username = props.getproperty( "jdbc.username" ); string password = props.getproperty( "jdbc.password" ); response.getwriter().println( "讀取web-inf目錄下的jdbc目錄中的db4.properties配置文件" ); response.getwriter().println(messageformat.format( "driver={0},url={1},username={2},password={3}" , driver,url, username, password)); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { } } |
3.配置servlet(web.xml)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?xml version= "1.0" encoding= "utf-8" ?> <web-app xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns= "http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "webapp_id" version= "3.0" > <display-name>javareaderfile</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file> default .html</welcome-file> <welcome-file> default .htm</welcome-file> <welcome-file> default .jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>filereader</servlet-name> <servlet- class >com.xia.filereader.filereader</servlet- class > </servlet> <servlet-mapping> <servlet-name>filereader</servlet-name> <url-pattern>/filereader</url-pattern> </servlet-mapping> </web-app> |
4.測試
方式二:采用resourcebundle類讀取配置信息
優(yōu)點(diǎn)是:可以以完全限定類名的方式加載資源后,直接的讀取出來,且可以在非web應(yīng)用中讀取資源文件。
缺點(diǎn):只能加載類src下面的資源文件且只能讀取.properties文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
/** * 獲取指定配置文件中所有的數(shù)據(jù) * @param propertyname * 調(diào)用方式: * 1.配置文件放在resource源包下,不用加后綴 * propertiesutil.getallmessage("message"); * 2.放在包里面的 * propertiesutil.getallmessage("com.test.message"); * @return */ public static list<string> getallmessage(string propertyname) { // 獲得資源包 resourcebundle rb = resourcebundle.getbundle(propertyname.trim()); // 通過資源包拿到所有的key enumeration<string> allkey = rb.getkeys(); // 遍歷key 得到 value list<string> vallist = new arraylist<string>(); while (allkey.hasmoreelements()) { string key = allkey.nextelement(); string value = (string) rb.getstring(key); vallist.add(value); } return vallist; } |
方式三:采用classloader方式進(jìn)行讀取配置信息
優(yōu)點(diǎn)是:可以在非web應(yīng)用中讀取配置資源信息,可以讀取任意的資源文件信息
缺點(diǎn):只能加載類src下面的資源文件,不適合裝載大文件,否則會導(dǎo)致jvm內(nèi)存溢出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
package com.xia.filereader; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.util.properties; public class readbyclassloader { public static void main(string[] args) throws ioexception { readpropfilebyclassload(); } public static void readpropfilebyclassload() throws ioexception{ //讀取src下面config包內(nèi)的配置文件db3.properties inputstream in = readbyclassloader. class .getclassloader().getresourceasstream( "config/db3.properties" ); bufferedreader br = new bufferedreader( new inputstreamreader(in)); properties props = new properties(); props.load(br); for (object s: props.keyset()){ system.out.println(s+ ":" +props.getproperty(s.tostring())); } } } |
方式四: propertiesloaderutils工具類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
/** * spring 提供的 propertiesloaderutils 允許您直接通過基于類路徑的文件地址加載屬性資源 * 最大的好處就是:實(shí)時加載配置文件,修改后立即生效,不必重啟 */ private static void springutil(){ properties props = new properties(); while ( true ){ try { props=propertiesloaderutils.loadallproperties( "message.properties" ); for (object key:props.keyset()){ system.out.print(key+ ":" ); system.out.println(props.get(key)); } } catch (ioexception e) { system.out.println(e.getmessage()); } try {thread.sleep( 5000 );} catch (interruptedexception e) {e.printstacktrace();} } } |
修改properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
/** * 傳遞鍵值對的map,更新properties文件 * * @param filename * 文件名(放在resource源包目錄下),需要后綴 * @param keyvaluemap * 鍵值對map */ public static void updateproperties(string filename,map<string, string> keyvaluemap) { //getresource方法使用了utf-8對路徑信息進(jìn)行了編碼,當(dāng)路徑中存在中文和空格時,他會對這些字符進(jìn)行轉(zhuǎn)換,這樣, //得到的往往不是我們想要的真實(shí)路徑,在此,調(diào)用了urldecoder的decode方法進(jìn)行解碼,以便得到原始的中文及空格路徑。 string filepath = propertiesutil. class .getclassloader().getresource(filename).getfile(); properties props = null ; bufferedwriter bw = null ; try { filepath = urldecoder.decode(filepath, "utf-8" ); log.debug( "updateproperties propertiespath:" + filepath); props = propertiesloaderutils.loadproperties( new classpathresource(filename)); log.debug( "updateproperties old:" +props); // 寫入屬性文件 bw = new bufferedwriter( new outputstreamwriter( new fileoutputstream(filepath))); props.clear(); // 清空舊的文件 for (string key : keyvaluemap.keyset()) props.setproperty(key, keyvaluemap.get(key)); log.debug( "updateproperties new:" +props); props.store(bw, "" ); } catch (ioexception e) { log.error(e.getmessage()); } finally { try { bw.close(); } catch (ioexception e) { e.printstacktrace(); } } } |
總結(jié)
以上所述是小編給大家介紹的javaweb讀取配置文件的四種方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/zywglove/article/details/79579677