Properties - 图1

读取配置文件

  1. import java.io.FileInputStream;
  2. import java.io.IOException;
  3. import java.util.Properties;
  4. public class PropertiesTest {
  5. public static void main(String[] args) throws IOException {
  6. String f = "setting.properties";
  7. Properties p = new Properties();
  8. p.load(new FileInputStream(f));
  9. String url = p.getProperty("url");
  10. String password = p.getProperty("password");
  11. System.out.println(url + " : " + password);
  12. }
  13. }

如果有多个配置文件,可以使用 load 多次读取,如果 key 相同,那么后面的会覆盖前面的

  1. Properties props = new Properties();
  2. props.load(getClass().getResourceAsStream("/common/setting.properties"));
  3. props.load(new FileInputStream("C:\\conf\\setting.properties"));

写入配置文件

  1. Properties props = new Properties();
  2. props.setProperty("url", "http://www.liaoxuefeng.com");
  3. props.setProperty("language", "Java");
  4. props.store(new FileWriter("setting2.properties"), "这是写入的properties注释");