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);
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)来获取信息。