获取.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编码