首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java读取配置文件的方式

java读取配置文件的方式

作者头像
OPice
发布2019-10-23 17:50:30
1.5K0
发布2019-10-23 17:50:30
举报
文章被收录于专栏:D·技术专栏D·技术专栏
  • 使用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);
}
  • ResourceBundle
public static String getProperties(String key) throws Exception {
        //config为属性文件名,放在包com.test.config下,如果是放在src下,直接用config即可
        ResourceBundle resource = ResourceBundle.getBundle("application");
        return resource.getString(key);
    }
  • 使用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);
    }

@Value注解

@Value(${"logging.path"})
private String logPath;
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.09.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档