美文网首页
java读取配置文件的方式

java读取配置文件的方式

作者: OPice | 来源:发表于2019-09-25 12:47 被阅读0次
  1. 使用ClassLoader加载properties配置文件生成对应的输入流
public static String getProperties(String key) throws Exception {
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream("application.properties");
        // 使用properties对象加载输入流
        properties.load(in);
        //获取key对应的value值
        return properties.getProperty(key);
}
  1. ResourceBundle
public static String getProperties(String key) throws Exception {
        //config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
        ResourceBundle resource = ResourceBundle.getBundle("application");
        return resource.getString(key);
    }
  1. 使用InPutStream流读取properties文件
 public static String getProperties(String key) throws Exception {
        Properties properties = new Properties();
        // 使用InPutStream流读取properties文件
        BufferedReader bufferedReader = new BufferedReader(new FileReader("E:/config.properties"));
        properties.load(bufferedReader);
        // 获取key对应的value值
        return properties.getProperty(key);
    }

Spring支持文件读取方式

public static String getProperties(String key) throws Exception{
        Resource resource = new ClassPathResource("application.properties");
        Properties prop = PropertiesLoaderUtils.loadProperties(resource);
        return prop.getProperty(key);
    }
  1. @Value注解
@Value(${"logging.path"})
private String logPath;

相关文章

网友评论

      本文标题:java读取配置文件的方式

      本文链接:https://www.haomeiwen.com/subject/zxphyctx.html