方式一:采用servletcontext读取
获取配置文件的realpath,然后通过文件流读取出来或者通过方法getreasurceasstream()。
因为是用servletcontext读取文件路径,所以配置文件可以放入在web-inf的classes目录中,也可以在应用层级及web-inf的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-inf及web-root下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。
1.首先创建一个动态的javaweb项目,项目目录如下:
2.创建一个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进行解码;
* 这样就不会出现中文乱码了
*/
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类读取配置信息
优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非web应用中读取资源文件。
缺点:只能加载类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
|
/**
* 获取指定配置文件中所有的数据
* @param propertyname
* 调用方式:
* 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方式进行读取配置信息
优点是:可以在非web应用中读取配置资源信息,可以读取任意的资源文件信息
缺点:只能加载类src下面的资源文件,不适合装载大文件,否则会导致jvm内存溢出
|
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包内的配置文件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 允许您直接通过基于类路径的文件地址加载属性资源
* 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启
*/
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对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样,
//得到的往往不是我们想要的真实路径,在此,调用了urldecoder的decode方法进行解码,以便得到原始的中文及空格路径。
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();
}
}
}
|
总结
以上所述是小编给大家介绍的javaweb读取配置文件的四种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
原文链接:http://blog.csdn.net/zywglove/article/details/79579677
相关文章
- 64M VPS建站:是否适合初学者操作和管理? 2025-06-10
- ASP.NET自助建站系统中的用户注册和登录功能定制方法 2025-06-10
- ASP.NET自助建站系统的域名绑定与解析教程 2025-06-10
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
-
2025-05-27 91
-
2025-05-29 18
-
2025-06-04 55
-
2025-06-04 46
-
2025-05-29 51



