Setting System properties from command-line

Code Sample:

public static void main(String[] args)
{
  String property = System.getProperty("my.text");
  System.out.println(property);
}

Execution:

java -Dmy.text="Hello World." -jar /home/user/application.jar

Note: With java -D you can set every property you like except the reserved ones, listed in [post id=2219]Java System Properties[/post].

You can set multiple properties with the following command:

java -Dmy.text="Hello World." -Dmy.ide="NetBeans IDE" -Dmy.browser="Mozilla Firefox" -jar /home/user/application.jar

Datei innerhalb einer JAR Datei lesen

Kurzer Code-Schnippsel, um eine properties-Datei, die in einem Paket aus einer JAR-Datei steckt, einzulesen:

1
2
3
4
5
6
7
8
9
10
    Properties properties = new Properties();
    try
    {
      InputStream is = this.getClass().getClassLoader().getResourceAsStream("com/oberprima/upload/client/configuration/config.properties");
      properties.load(is);
    }
    catch (IOException ex)
    {
      System.out.println(ex.getLocalizedMessage());
    }

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"));

Java System Properties

Über System.getProperty kann Java bestimme Informationen über das System, auf welchem der aktuelle Java Sourcecode ausgeführt wird, liefern. Zum Anzeigen des Benutzerverzeichnisses würde folgender Code ausreichen:

1
2
String userDirectory = System.getProperty("user.home");
System.out.println(userDirectory);

Die Ausgabe wäre in meinem Fall:

C:\Users\bennyn

Folgende System Properties sind verfügbar:
Java System Properties weiterlesen