Java读取properties配置文件常用方法

来源:互联网 发布:mac怎么清理其他内存 编辑:程序博客网 时间:2024/05/29 09:33

在开发中对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());}}

测试:

@Testpublic 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");

测试:

@Testpublic 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"));}




2 0
原创粉丝点击