Propertes文件的读取和保存(保留注释)

读取比较简单~~

保存的时候,如果使用默认的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); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值