Häufig ist es notwendig, dass Programmeinstellungen in eine Konfigurationsdatei gespeichert und wieder geladen werden können. Mit Hilfe des Properties Objektes können solche Dateien im Format:
#Kommentarzeile #Mon Jan 12 12:00:00 MYT 2013 database=localhost user=Horst password=geheim
oder
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Kommentarzeile</comment> <entry key="database">localhost</entry> <entry key="user">Horst</entry> <entry key="password">geheim</entry> </properties>
erzeugt werden.
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Speichert Konfiguration
* @param filename Dateiname der Konfigurationsdatei
*/
public void SaveConfig(String filename)
{
Properties prop = new Properties();
FileOutputStream fos = null;
try
{
// Properties setzen
prop.setProperty("database", "localhost");
prop.setProperty("user", "Horst");
prop.setProperty("password", "geheim");
// 1. Einstellungen speichern als einfache Datei
fos = new FileOutputStream(filename);
prop.store(fos, "Kommentarzeile");
// 2. Einstellungen speichern als XML-Datei im Format UTF-8
prop.storeToXML(new FileOutputStream(filename), "Kommentarzeile", "UTF-8");
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null) fos.close();
}
}
/**
* Läd Konfiguration
* @param filename Dateiname der Konfigurationsdatei
*/
public void LoadConfig(String filename)
{
Properties prop = new Properties();
FileInputStream fis = null;
try
{
// 1. Einstellungen aus einfacher Datei laden
fis = new FileInputStream(filename);
prop.load(fis);
// 2. oder Einstellungen aus XML-Datei laden
//prop.loadFromXML(fis);
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("user"));
System.out.println(prop.getProperty("password"));
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (fis != null) fis.close();
}
}
Weiterführende Links
- Siehe auch: Tutorialspoint
- Siehe auch: Java ist auch eine Insel