1 /** 2 * 向properties文件写入属性 3 * 4 * @param filePath 5 * @param parameterName 6 * @param parameterValue 7 */ 8 public static void writePropertiesFile(String filePath, String parameterName, String parameterValue) { 9 Properties prop = new Properties();10 try {11 InputStream fis = new FileInputStream(filePath);12 // 从输入流中读取属性列表(键和元素对)13 prop.load(fis);14 // 调用 Hashtable 的方法 put。使用 getProperty 方法提供并行性。15 // 强制要求为属性的键和值使用字符串。返回值是 Hashtable 调用 put 的结果。16 OutputStream fos = new FileOutputStream(filePath);17 prop.setProperty(parameterName, parameterValue);18 // 以适合使用 load 方法加载到 Properties 表中的格式,19 // 将此 Properties 表中的属性列表(键和元素对)写入输出流20 prop.store(fos, "Update '" + parameterName + "' value");21 } catch (IOException e) {22 System.err.println("Visit " + filePath + " for update " + parameterName + " value error");23 }24 }25 26 /**27 * 读取properties文件内容28 * 29 * @param filePath30 * @param parameterName31 * @return32 */33 public static String readProperties(String filePath, String parameterName) {34 Properties prop = new Properties();35 try {36 InputStream fis = new FileInputStream(filePath);37 // 从输入流中读取属性列表(键和元素对)38 prop.load(fis);39 return String.valueOf(prop.get(parameterName));40 } catch (IOException e) {41 System.err.println("Visit " + filePath + " for query " + parameterName + " value error");42 }43 return null;44 }
使用prop.load()和prop.store()读取和写入properties文件时, 会出现乱序的问题,因为Properties继承于<,>, 另外之前的注释也会丢失.可改用直接当成文本文件处理,
1 /** 2 * 向properties文件写入属性. 由于使用prop.load(fis)读取properties文件内容后再写入会乱序, 改用直接操作文件 3 * 4 * @param filePath 5 * @param parameterName 6 * @param parameterValue 7 */ 8 public static void writePropertiesFile(String filePath, String parameterName, String parameterValue) { 9 try {10 File file = new File(filePath);11 ListnewLines = new ArrayList ();12 for (Object line : FileTools.readLines(file)) {13 if (line.toString().startsWith(parameterName + "=")) {14 newLines.add(parameterName + "=" + parameterValue);15 } else {16 newLines.add(line.toString());17 }18 }19 FileTools.writeLines(file, newLines);20 } catch (IOException e) {21 System.err.println("Visit " + filePath + " for update " + parameterName + " value error");22 }23 }