Konfigurasyon dosyaları, sonradan düzenlenebilir çeşitli ayar verilerine ve pek değişmeyeceği düşünülen bağlantı verilerine sonradan kolayca erişilebilip kod üzerinde oynamaksızın programın işleyişini değiştirmek amacıyla kullanabileceğimiz dosya yapılarıdır. Buradaki verilere java.util.Properties sınıfını kullanarak ulaşılabilir.
Kolay bir örnek dosya aşağıdaki gibidir.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.util.Properties; | |
public class PropertiesMain { | |
/** | |
* @param args | |
* @author tolpp | |
*/ | |
public static void main(String[] args) { | |
addToProperties(); | |
printProperties(); | |
} | |
private static void addToProperties() { | |
Properties prop = new Properties(); | |
try { | |
// property verileri atanır | |
prop.setProperty("database", "default"); | |
prop.setProperty("dbuser", "root"); | |
prop.setProperty("dbpassword", ""); | |
// config dosyası kaydedilir. | |
prop.store(new FileOutputStream("config.properties"), null); | |
} catch (IOException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
private static void printProperties() { | |
Properties prop = new Properties(); | |
try { | |
prop.load(new FileInputStream("config.properties")); | |
System.out.println("=== Istenilen Propertyler ==="); | |
System.out.println(prop.getProperty("database")); | |
System.out.println(prop.getProperty("dbuser")); | |
System.out.println(prop.getProperty("dbpassword","")); //dbpassword propertysi yoksa default olarak bos string doner | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
İşlem sonrasında config.properties dosyasının içeriği de aşağıdaki gibi olacaktır :
dbpassword=password
database=default
dbuser=root