博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Java的Properties文件读写笔记

Posted on 2017-12-26 22:20  羽系  阅读(183)  评论(0编辑  收藏  举报

获取.properties文件参数的代码

【注意】x.properties文件在class文件夹中,如果是web项目,就在WEB-INF/classes文件夹中,不过如果放在src下,编译后JVM会把它自动加载到classpath中。

    public String getPropertyByField(String fieldName) {
        Properties info = new Properties();
        try (InputStream prosStream = getClass().getClassLoader().getResourceAsStream("x.properties");){
            info.load(prosStream);
            String result = info.getProperty(fieldName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null;
    }

properties文件书写的注意事项

  • 格式为 key = value,取出来都默认是字符串类型
  • 不需要额外加"",如果value代表文件路径,需要加转义字符
  • 一般一行代表一对键值
  • 可以用#注释
  • 中文都会自动转化位Unicode编码