java使用Properties读写配置文件


Java中提供了类 java.util.Properties类用来操作配置文件。在Java程序中可以很方便的读写配置文件。
在线文档:Properties (Java Platform SE 8 )

1. 读配置文件

在开发数据库的项目时,例如我们将数据库的连接信息存放到如下配置文件中 db.properties, 并放在项目的src/main/resources目录下面。

jdbcName=com.mysql.jdbc.Driver
dbUrl=jdbc:mysql://localhost:3306/db_note?useUnicode=true&characterEncoding=utf8&&serverTimezone=GMT%2B8&useSSL=false
dbUsername=root
dbPassword=123456

在Java代码中,我们可以通过以下方法去获取配置信息。


@Test
public void checkRead() {
try (FileInputStream fis = new FileInputStream("src/main/resources/db.properties")) {
Properties properties = new Properties();
properties.load(fis);

// 从配置文件获取值
String jdbcName = properties.getProperty("jdbcName");
String dbUrl = properties.getProperty("dbUrl");
String dbUsername = properties.getProperty("dbUsername");
String dbPassword = properties.getProperty("dbPassword");

System.out.println("jdbcName = " + jdbcName);
System.out.println("dbUrl = " + dbUrl);
System.out.println("dbUsername = " + dbUsername);
System.out.println("dbPassword = " + dbPassword);

// 也可以遍历所有配置项
System.out.println("\n========================\n");
properties.forEach((k,v)-> System.out.println(k + " --> " + v));

// 还可以分别获取所有key和value
System.out.println("\n========================\n");
System.out.println(properties.keySet());
System.out.println(properties.values());

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

注:在获取配置文件的方式上,除了给相对于工程的路径来说,我们也可以从Classpath获取。因为IDE会把src/main/resources添加到Classpath中去。如下代码所示:

@Test
public void checkRead() {
try (InputStream is = TestProperties.class.getClassLoader().getResourceAsStream("db.properties")) {
if (is == null) {
throw new RuntimeException("无法找到配置文件!");
}
Properties properties = new Properties();
properties.load(is);
// ... 其他不变...
}
}

2. 写配置文件

同样地,我们也可以利用代码去生成对应的配置文件。

@Test
public void checkWrite() {
try (FileOutputStream fos = new FileOutputStream("src/main/resources/db2.properties")) {
Properties prop = new Properties();

// 设置属性值
prop.setProperty("dbUrl", "localhost");
prop.setProperty("dbUsername", "root");
prop.setProperty("dbPassword", "123456");

// 保存配置文件, 第二个参数是comment,会添加到配置的第一行
prop.store(fos, "MySQL DB config");

System.out.println(prop);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

最后会生成如下配置文件:

#MySQL DB config
#Tue Jul 27 09:30:54 CST 2021
dbUsername=root
dbPassword=123456
dbUrl=localhost

文章作者: IT神助攻
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 IT神助攻 !
  目录