• Java读取properties配置文件经常用法


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




  • 相关阅读:
    Mapreduce实例——求平均值
    Mapreduce实例——单表join
    《短码之美》读书笔记1
    Mapreduce实例——Map端join使用addCacheFile()方法报错,找不到文件
    Mapreduce实例——Map端join
    C# 异常捕获
    Mapreduce实例——排序
    无名
    数据库设计体会
    oracle 删除表空间错误 提示:ora02429:无法删除用于强制唯一/主键的索引。
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/6706385.html
Copyright © 2020-2023  润新知