JAVA从入门到精通之JavaWeb读取配置文件的四种方法[Java代码]
龚超 2018-07-18 来源 : 阅读 994 评论 0

摘要:本文主要向大家介绍了JAVA从入门到精通的JavaWeb读取配置文件的四种方法,通过具体的内容向大家展示,希望对大家在JAVA从入门到精通的路上走的更远。

本文主要向大家介绍了JAVA从入门到精通的JavaWeb读取配置文件的四种方法,通过具体的内容向大家展示,希望对大家在JAVA从入门到精通的路上走的更远。

方式一:采用ServletContext读取

获取配置文件的realpath,然后通过文件流读取出来或者通过方法getReasurceAsStream()。

因为是用ServletContext读取文件路径,所以配置文件可以放入在WEB-INF的classes目录中,也可以在应用层级及WEB-INF的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在WEB-INF及Web-Root下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在servlet外面应用读取配置信息。

1.首先创建一个动态的javaweb项目,项目目录如下:


2.创建一个servlet(FileReader.java)


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("


");

readWebRootDirPropCfgFile(response);//读取WebRoot目录下的db2.properties配置文件

response.getWriter().println("


");

readSrcSourcePackPropCfgFile(response);//读取src目录下的config目录中的db3.properties配置文件

response.getWriter().println("


");

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=小贝,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=小贝,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=小贝,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=小贝,username={2},password={3}",

driver,url, username, password));

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

}

复制代码

3.配置servlet(web.xml)


javaReaderFile

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp


FileReader

com.xia.fileReader.FileReader


FileReader

/FileReader





复制代码

4.测试


方式二:采用ResourceBundle类读取配置信息

优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。

缺点:只能加载类src下面的资源文件且只能读取.properties文件。


/**

* 获取指定配置文件中所有的数据

* @param propertyName

* 调用方式:

* 1.配置文件放在resource源包下,不用加后缀

* PropertiesUtil.getAllMessage("message");

* 2.放在包里面的

* PropertiesUtil.getAllMessage("com.test.message");

* @return

*/

public static ListgetAllMessage(String propertyName) {

// 获得资源包

ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim());

// 通过资源包拿到所有的key

EnumerationallKey = rb.getKeys();

// 遍历key 得到 value

ListvalList = new ArrayList();

while (allKey.hasMoreElements()) {

String key = allKey.nextElement();

String value = (String) rb.getString(key);

valList.add(value);

}

return valList;

}

复制代码

方式三:采用ClassLoader方式进行读取配置信息

优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息

缺点:只能加载类src下面的资源文件,不适合装载大文件,否则会导致jvm内存溢出


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工具类


/**

* 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


/**

* 传递键值对的Map,更新properties文件

*

* @param fileName

* 文件名(放在resource源包目录下),需要后缀

* @param keyValueMap

* 键值对Map

*/

public static void updateProperties(String fileName,MapkeyValueMap) {

//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();

}

}

}

复制代码

总结

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!


本文由 @职坐标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论
本文作者 联系TA

擅长针对企业软件开发的产品设计及开发的细节与流程设计课程内容。座右铭:大道至简!

  • 370
    文章
  • 45102
    人气
  • 83%
    受欢迎度

已有24人表明态度,83%喜欢该老师!

进入TA的空间
求职秘籍 直通车
  • 资料领取 资料领取 资料领取
  • 答疑解惑 答疑解惑 答疑解惑
  • 技术交流 技术交流 技术交流
  • 职业测评 职业测评 职业测评
  • 面试技巧 面试技巧 面试技巧
  • 高薪秘笈 高薪秘笈 高薪秘笈
TA的其他文章 更多>>
WEB前端必须会的基本知识题目
经验技巧 93% 的用户喜欢
Java语言中四种遍历List的方法总结(推荐)
经验技巧 91% 的用户喜欢
Java语言之SHA-256加密的两种实现方法详解
经验技巧 75% 的用户喜欢
java语言实现把两个有序数组合并到一个数组的实例
经验技巧 75% 的用户喜欢
通过Java语言代码来创建view的方法
经验技巧 80% 的用户喜欢
其他海同师资 更多>>
吕益平
吕益平 联系TA
熟悉企业软件开发的产品设计及开发
孔庆琦
孔庆琦 联系TA
对MVC模式和三层架构有深入的研究
戴懿颢​
戴懿颢​ 联系TA
20年+嵌入式开发经验,精多语言 / 云 / 安全 / 数据库
郭自琦
郭自琦 联系TA
16年物联网经验,涉多项目,多校授课,出版书籍并研发IT教程
余承民
余承民 联系TA
8年开发+5年教学经验,指导数千名学员高薪就业
经验技巧30天热搜词 更多>>

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved