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));
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");
prop.store(fos, "MySQL DB config");
System.out.println(prop); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
最后会生成如下配置文件:
dbUsername=root dbPassword=123456 dbUrl=localhost
|