java 读取properties配置文件

java中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties文件中,可以用"#"来作注释,properties文件在Java编程中用到的地方很多,操作很方便。

读取properties文件的方式有很多,我从网上找到一些别人总结的方法

1、使用java.util.Properties类的load()方法

InputStream is = new BufferedInputStream(new FileInputStream(new File(properties文件所在路径));  
Properties properties = new Properties();  
properties.load(is);  
2、使用java.util.ResourceBundle类的getBundle()方法

ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());  
3、使用java.util.PropertyResourceBundle类的构造函数

InputStream is = new BufferedInputStream(new FileInputStream(name));  
ResourceBundle rb = new PropertyResourceBundle(is);  
4、使用class变量的getResourceAsStream()方法

InputStream in = 类名.class.getResourceAsStream(name);  
Properties p = new Properties();  
p.load(in);  
5、使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法

InputStream in = 类名.class.getClassLoader().getResourceAsStream(name);  
Properties p = new Properties();  
p.load(in);  
6、使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法

InputStream in = ClassLoader.getSystemResourceAsStream(name);  
Properties p = new Properties();  
p.load(in); 


这里是方法4的代码实例

package com.yuanding.common.util;

import java.io.InputStream;
import java.util.Properties;


public class Configure {

	static Properties pp;

	static{
		pp = new Properties();
		try {
			InputStream fps = Configure.class.getResourceAsStream("/config.properties");
			pp.load(fps);
			fps.close();
		} catch (Exception e) {
			System.out.print("读取config.properties文件异常!");
			e.printStackTrace();
		}
	}
	public static String values(String key) {
		String value = pp.getProperty(key);
		if (value != null) {
			return value;
		} else {
			return null;
		}
	}
}

我们在开发中可以写一个读取properties文件的工具类,通过调用方法来读取配置文件信息。

我们读取配置文件的信息可以写一个静态方法来获取,因为properties文件的信息都是key-value键值对的形式

如:

public static class config{
		//ios设备apiKey
		public static String IOS_APIKEY = values("IOS_APIKEY");
		//ios设备secretKey
		public static String IOS_SECRETKEY = values("IOS_SECRETKEY");
		//android设备apiKey
		public static String ANDROID_APIKEY = values("ANDROID_APIKEY");
		//android设备secretKey
		public static String ANDROID_SECRETKEY = values("ANDROID_SECRETKEY");
		//是否是开发环境
		public static int IS_DEVELOPMENT = values("IS_DEVELOPMENT") == null ? 1 : Integer.parseInt(values("IS_DEVELOPMENT"));
		//android分组tag
		public static String ANDROID_TAG = values("ANDROID_TAG");
		//ios分组tag
		public static String IOS_TAG = values("IOS_TAG");
}
这样我们就可以获取我们需要的配置文件信息,而且还很整齐,获取值只要调用如(类名.config.IOS_APIKEY)来获取信息。






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值