java获取配置文件_JAVA读取配置文件的方法

JAVA读取配置文件的方法

普通java项目

1、classLoader

//主要通过当前类的加载器加载classpath下的资源文件,局限是classpath下的

//getResourceAsStream的路径相当于${classpath}/ 参数相对于这个路径来的

Properties properties = new Properties();

InputStream in = PaySupportUtils.class.getClassLoader()

.getResourceAsStream("pay.properties");

try {

properties.load(in);

String url = properties.getProperty("pay.url");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

//ClassLoader.getResource(), 参数为空是当前class的路径,'/'为classpath根路径

String path = PaySupportUtils.class.getResource("").getPath();

String path2 = PaySupportUtils.class.getResource("/").getPath();

2、通过InputStream进行读取文件

//可以读取任意路径的文件

Properties properties = new Properties();

// 使用InPutStream流读取properties文件

BufferedReader bufferedReader =

new BufferedReader(new FileReader("E:/config.properties"));

properties.load(bufferedReader);

properties.getProperty(String key);

3、使用ResourceBundle进行读取

//这种读取方式跟使用ClassLoader基本一致,路径也是classpath/

ResourceBundle bundle = ResourceBundle.getBundle("static/pay2");

bundle.getString("pay.userid")

4、使用Spring提供的PropertiesLoaderUtils.loadAllProperties

//跟ClassLoader、ResourceBundle 路径一致都是classpath/为根路径的

//还有一个好处是Spring进行了加强,可以对文件的内容改变进行实时体现,其他的方法不行

Properties ps = PropertiesLoaderUtils.loadAllProperties("pay.properties");

ps.getProperty("pay.money", "10000");

WEB项目

1、采用ServletContext读取放在src和WEB-INF中的配置文件

//跟其他的没有什么区别,不过这个是获取文件的实际路径,然后进行流读取,路径以 / 开头

String path = "/WEB-INF/classes/db1.properties";

InputStream in = this.getServletContext().getResourceAsStream(path);

2、使用与普通java项目一样的获取方式

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值