在开发中对properties文件的操作还是蛮常常的。所以总结了几种操作方法,为后面的开发能够进行參考。
1、通过java.util.ResourceBundle类来读取
这边測试用到了枚举类进行传入文件的key值,然后获取value,能够进行灵活的配置。
通过这样的方式读取properties文件不须要加.properties后缀名,仅仅需文件名称就可以,假设有放在某一个包下,要加包的限定名。如放在com.frame.util包下,则要路径要用com/fram/util
config.properties:
CONFIGFILE_DIR=F:\configDir //两个斜杠是转义用
枚举类ConfigFileEnum.java
public enum ConfigFileEnum { CONFIGFILE_DIR("CONFIGFILE_DIR"); private String name = null; ConfigFileEnum(String name){ this.name = name; } public String getName(){ return this.name; } }
读取配置文件类ConfigUtil.java
public class ConfigUtil { private static ResourceBundle resourceBundle = ResourceBundle.getBundle("config", Locale.ENGLISH); public static String getConfigKey(ConfigFileEnum configFileEnum){ return resourceBundle.getString(configFileEnum.getName()); } }
測试:
@Test public void testProperties(){ String key = ConfigUtil.getConfigKey(ConfigFileEnum.CONFIGFILE_DIR); System.out.println(key); }
2、通过jdk提供的java.util.Properties类
在使用properties文件之前,还须要载入属性文件,它提供了两个方法:load和loadFromXML。
load有两个方法的重载:load(InputStream inStream)、load(Reader reader)。所以。可依据不同的方式来载入属性文件。
下面提供三种方法:
1、通过当前类载入器的getResourceAsStream方法获取
InputStream inStream = TestHttpClient.class.getClassLoader().getResourceAsStream("config.properties");
2、从文件获取
InputStream inStream = new FileInputStream(new File("D:\dir\Frame\src\config.properties"));
3、通过类载入器实现,和第一种一样
InputStream inStream = ClassLoader.getSystemResourceAsStream("config.properties");
測试:
@Test public void testProperties() throws IOException{ Properties p = new Properties(); InputStream inStream = TestHttpClient.class.getClassLoader().getResourceAsStream("config.properties"); p.load(inStream); System.out.println(p.get("CONFIGFILE_DIR")); }