maven项目添加配置文件

时间:2021-09-14 23:26:40

1. 在src/main/resources下新建param.properties

2. 在param.properties文件中添加

  mqtt.host=tcp://127.0.0.1:1883
  mqtt.username=xxxxxx
  mqtt.password=xxxxxxx

3. 在pom.xml中添加

</resources>

  <resource>
    <directory>src/main/resources</directory>
    <includes>
      <include>**/*.xml</include>
      <include>**/*.properties</include>
    </includes>
  </resource>
</resources>

4. 在java文件中

try {

  Properties prop = new Properties();
  String resouces = "param.properties";
  InputStream in = Resources.getResourceAsStream(resouces);
  prop.load(in);
  Iterator<String> it = prop.stringPropertyNames().iterator();
  while (it.hasNext()) {
    String s = it.next();
    if (s.equals("mqtt.host")) {
      String s1 = prop.getProperty("mqtt.host");
    }else if(s.equals("mqtt.username")) {
      String s2 = prop.getProperty("mqtt.username");
    }else if(s.equals("mqtt.password")) {
      String s3 = prop.getProperty("mqtt.password");
    }
  }
  in.close();
}catch(Exception e) {

  System.out.println("Exception:");
  e.printStackTrace();
}