// -----------------------------------------------------------------------------
// PropertyFiles.java
// -----------------------------------------------------------------------------
import java.util.Properties;
import java.util.Enumeration;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileInputStream;
/**
* -----------------------------------------------------------------------------
* Used to provide an example of how to get/modify/save Properties files
* while preserving comments in the file.
* -----------------------------------------------------------------------------
*/
public class PropertyFiles {
private static void printProperties(Properties p, String s) {
System.out.println();
System.out.println();
System.out.println(s);
System.out.println();
p.list(System.out);
System.out.println();
}
private static void saveProperties(Properties p, String fileName) {
OutputStream outPropFile;
try {
outPropFile = new FileOutputStream(fileName);
p.store(outPropFile, "Properties File to the Test Application");
outPropFile.close();
} catch (IOException ioe) {
System.out.println("I/O Exception.");
ioe.printStackTrace();
System.exit(0);
}
}
private static Properties loadProperties(String fileName) {
InputStream inPropFile;
Properties tempProp = new Properties();
try {
inPropFile = new FileInputStream(fileName);
tempProp.load(inPropFile);
inPropFile.close();
} catch (IOException ioe) {
System.out.println("I/O Exception.");
ioe.printStackTrace();
System.exit(0);
}
return tempProp;
}
private static Properties alterProperties(Properties p) {
Properties newProps = new Properties();
Enumeration enumProps = p.propertyNames();
String key = "";
while ( enumProps.hasMoreElements() ) {
key = (String) enumProps.nextElement();
if (!key.equals("fake_entry")) {
if (key.equals("log_level")) {
newProps.setProperty(key, "3");
} else {
newProps.setProperty(key, p.getProperty(key));
}
}
}
return newProps;
}
/**
* Sole entry point to the class and application.
* @param args Array of String arguments.
*/
public static void main(String[] args) {
final String PROPFILE= "Application.properties";
Properties myProp;
Properties myNewProp;
// Input Properties File
myProp = loadProperties(PROPFILE);
printProperties(myProp, "Loaded Properties");
// Modified Properties File
myNewProp = alterProperties(myProp);
printProperties(myNewProp, "After Modifying Properties");
saveProperties(myNewProp, PROPFILE);
}
}
This post has been edited by jms9900: 04 June 2008 - 07:24 AM

New Topic/Question
Reply



MultiQuote









|