Properties File in Java öffnen und auslesen

Konfigurationen für eine Anwendung sollte man nach Möglichkeit in einer externen Datei auslagern. Java unterstützt dieses Konzept durch sog. „Properties“, die in einer Datei gespeichert werden und nach dem Key/Value-Prinzip ausgelesen werden können. Eine einfache .properties-Datei könnte wie folgt aussehen:

connection.properties

1
2
3
4
5
user=root
password=my-secret-password
host=localhost
port=3306
database=my-database

Den Wert „root“ des Schlüssels „user“ kann man dann mit folgendem Code-Schnippsel auslesen:

1
2
3
4
5
6
7
8
9
10
11
File propertiesFile = new File("./src/resources/connection.properties");
Properties properties = new Properties();
 
if(propertiesFile.exists())
{
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile));
  properties.load(bis);
  bis.close();  
}
 
System.out.println(properties.getProperty("user"));

Mit Java 7 geht das Ganze noch etwas kompakter (dank try-with-resources):

1
2
3
4
5
6
7
8
9
10
File propertiesFile = new File("./src/resources/connection.properties");
Properties properties = new Properties();
 
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(propertiesFile))) {
  properties.load(bis);
} catch (Exception ex) {
  //
}
 
System.out.println(properties.getProperty("user"));