/**
* Update the key's value to new value ,and write back to the Configuration
* file
*
* @param configFilePath
* Configuration file
* @param key
* the key
* @param value
* the new value
*/
publicstatic Boolean updateProperty(String configFilePath, String key, String value) {
// Read File
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(configFilePath));
} catch (FileNotFoundException e) {
Log.getInstance().fine("Can not find file: " + configFilePath + "."); //$NON-NLS-1$ //$NON-NLS-2$
}
StringBuilder builder = new StringBuilder();
String tempLine;
String tempValue;
// Find the property and update
try {
while ((tempLine = reader.readLine()) != null) {
if (tempLine.trim().startsWith(COMMENT_FALG)) {
builder.append(tempLine).append(LINE_SEPARATOR);
continue;
}
if (tempLine.contains(key)) {
tempValue = tempLine.trim().substring(key.length());
if (tempValue.trim().startsWith(EQUAL_FLAG)) {
tempLine = key + EQUAL_FLAG + value;
}
}
builder.append(tempLine).append(LINE_SEPARATOR);
}
reader.close();
} catch (IOException e) {
Log.getInstance().fine("Read configuration file: " + configFilePath + " error."); //$NON-NLS-1$ //$NON-NLS-2$
e.printStackTrace();
}
// Update File
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(configFilePath));
writer.append(builder.toString());
writer.close();
} catch (IOException e) {
Log.getInstance().fine("Update configuration file: " + configFilePath + " error."); //$NON-NLS-1$ //$NON-NLS-2$
}
returntrue;
}
/**
* Get value from configuration file by key
*
* @param configFilePath
* configuration file path
*
* @param key
* the key
*
* @return the value
*/
publicstatic String getProperty(String configFilePath, String key) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(configFilePath));
} catch (FileNotFoundException e) {
Log.getInstance().fine("Can not find file: " + configFilePath + "."); //$NON-NLS-1$ //$NON-NLS-2$
} catch (IOException e) {
Log.getInstance().fine("Error read configuration file: " + configFilePath + " ."); //$NON-NLS-1$ //$NON-NLS-2$
}
return prop.getProperty(key);
}
--转自
该贴由hui.chen转至本版2015-7-30 15:23:14