读取比较简单~~
保存的时候,如果使用默认的property.store()方法,会把所有的注释都忽略~
所以自己采用读取文件的方式,来实现保存property~
/** * 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 */ public static 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$ } return true; } /** * Get value from configuration file by key * * @param configFilePath * configuration file path * * @param key * the key * * @return the value */ public static 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); }