Java 17 Recipes


-11. Reading Property Files


Download 3.2 Mb.
Pdf ko'rish
bet164/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   160   161   162   163   164   165   166   167   ...   245
Bog'liq
Java 17 Recipes

8-11. Reading Property Files
 Problem
You want to establish some configurational settings for your application. You want 
to modify the settings manually or programmatically. Moreover, you want some 
configurations to be changed without recompiling and redeploying.
 Solution
Create a properties file to store the application configurations. Using the Properties 
object, load properties stored within the properties file for application processing. 
Properties can also be updated and modified within the properties file. The following 
example demonstrates how to read a properties file named properties.conf, load the 
values for application use, and finally set a property and write it to the file.
ChApTer 8 InpuT And OuTpuT


323
public class Ch_8_11_PropertiesExample {
private void start() {
File file = new File("properties.conf");
Properties properties = null;
try {
if (!file.exists()) {
file.createNewFile();
}
properties = new Properties();
properties.load(new FileInputStream("properties.conf"));
} catch (IOException e) {
e.printStackTrace();
}
boolean shouldWakeUp = false;
int startCounter = 100;
String shouldWakeUpProperty = properties.
getProperty("ShouldWakeup");
shouldWakeUp = (shouldWakeUpProperty == null) ? false : Boolean.par
seBoolean(shouldWakeUpProperty.trim());
String startCounterProperty = properties.
getProperty("StartCounter");
try {
startCounter = Integer.parseInt(startCounterProperty);
} catch (Exception e) {
System.out.println("Couldn't read startCounter, defaulting to " 
+ startCounter);
}
String dateFormatStringProperty = properties.
getProperty("DateFormatString", "MMM dd yy");
System.out.println("Should Wake up? " + shouldWakeUp);
System.out.println("Start Counter: " + startCounter);
System.out.println("Date Format String:" + 
dateFormatStringProperty);
//setting property
properties.setProperty("StartCounter", "250");
ChApTer 8 InpuT And OuTpuT


324
try {
properties.store(new FileOutputStream("properties.conf"), 
"Properties Description");
} catch (IOException e) {
e.printStackTrace();
}
properties.list(System.out);
}
public static void main(String[] args) {
Ch_8_11_PropertiesExample propertiesExample = new Ch_8_11_
PropertiesExample();
propertiesExample.start();
}
}
An output is:
Should Wake up? false
Start Counter: 250
Date Format String:MMM dd yy
-- listing properties --
StartCounter=250

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   160   161   162   163   164   165   166   167   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling