原文地址:http://blog.csdn.net/benbenxiongyuan/article/details/53006097

参考地址:http://www.iteye.com/topic/156474

Properties调用store方法保存时,会把文件中原来的注释给冲掉,而且顺序会发生错乱,网上查找解决方案时,有人遇到了相同的问题,并给出了解决方案。

如下:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties; /**
* Properties调用store方法保存时,会把文件中原来的注释给冲掉,而且顺序会发生错乱,
* 网上查找解决方案时,有人遇到了相同的问题,并给出了解决方案
*
* 改进java.util.Properties文件读写类,在读取properties文件的时候把注释和顺序格式都记录下来,操作时候也把添加顺序记录了,
* 同时提供addComment()方法,可以添加注释,这样,经过处理的properties的可读性就能继续保持下来了,实现了SafeProperties.java,代码如下:
* @author Administrator
*
*/ @SuppressWarnings("all")
public class SafeProperties extends Properties { private static final long serialVersionUID = 5011694856722313621L; private static final String keyValueSeparators = "=: \t\r\n\f"; private static final String strictKeyValueSeparators = "=:"; private static final String specialSaveChars = "=: \t\r\n\f#!"; private static final String whiteSpaceChars = " \t\r\n\f"; private PropertiesContext context = new PropertiesContext(); public PropertiesContext getContext() {
return context;
} public synchronized void load(InputStream inStream) throws IOException { BufferedReader in; in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
// Get next line
String line = in.readLine();
// intract property/comment string
String intactLine = line;
if (line == null)
return; if (line.length() > 0) { // Find start of key
int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++)
if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
break; // Blank lines are ignored
if (keyStart == len)
continue; // Continue lines that end in slashes if they are not comments
char firstChar = line.charAt(keyStart); if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null)
nextLine = "";
String loppedLine = line.substring(0, len - 1);
// Advance beyond whitespace on new line
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++)
if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
break;
nextLine = nextLine.substring(startIndex, nextLine.length());
line = new String(loppedLine + nextLine);
len = line.length();
} // Find separation between key and value
int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\')
separatorIndex++;
else if (keyValueSeparators.indexOf(currentChar) != -1)
break;
} // Skip over whitespace after key if any
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++)
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break; // Skip over one non whitespace key value separators if any
if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++; // Skip over white space after other separators if any
while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(valueIndex, len) : ""; // Convert then store key and value
key = loadConvert(key);
value = loadConvert(value);
// memorize the property also with the whold string
put(key, value, intactLine);
} else {
// memorize the comment string
context.addCommentLine(intactLine);
}
} else {
// memorize the string even the string is empty
context.addCommentLine(intactLine);
}
}
} /*
* Converts encoded \uxxxx to unicode chars and changes special saved
* chars to their original forms
*/
private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len); for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
outBuffer.append('\t'); /* ibm@7211 */ else if (aChar == 'r')
outBuffer.append('\r'); /* ibm@7211 */
else if (aChar == 'n') {
/*
* ibm@8897 do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer.append('\n'); /* ibm@8897 ibm@7211 */
} else if (aChar == 'f')
outBuffer.append('\f'); /* ibm@7211 */
else
/* ibm@7211 */
outBuffer.append(aChar); /* ibm@7211 */
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
} public synchronized void store(OutputStream out, String header) throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null)
writeln(awriter, "#" + header);
List entrys = context.getCommentOrEntrys();
for (Iterator iter = entrys.iterator(); iter.hasNext();) {
Object obj = iter.next();
if (obj.toString() != null) {
writeln(awriter, obj.toString());
}
}
awriter.flush();
} private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
} private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\'))
slashCount++;
return (slashCount % 2 == 1);
} /*
* Converts unicodes to encoded \uxxxx and writes out any of the
* characters in specialSaveChars with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len * 2); for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
outBuffer.append('\\'); outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1)
outBuffer.append('\\');
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
} /**
* Convert a nibble to a hex character
*
* @param nibble
* the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
} /** A table of hex digits */
private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' }; public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
} public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
} public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
} class PropertiesContext {
private List commentOrEntrys = new ArrayList(); public List getCommentOrEntrys() {
return commentOrEntrys;
} public void addCommentLine(String line) {
commentOrEntrys.add(line);
} public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
} public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
} public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index, pe);
} public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
} class PropertyEntry {
private String key; private String value; private String line; public String getLine() {
return line;
} public void setLine(String line) {
this.line = line;
} public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
} /**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
} public String getKey() {
return key;
} public void setKey(String key) {
this.key = key;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
} /**
* @param comment
*/
public void addComment(String comment) {
if (comment != null) {
context.addCommentLine("#" + comment);
}
} }

java.util.Properties类,保存时保留注释及格式不变的更多相关文章

  1. 使用java.util.Properties类读写配置文件

    J2SE 1.5 以前的版本要求直接使用 XML 解析器来装载配置文件并存储设置,虽说也并非难事,相比 java.util.Properties却要做额外的解析工作.而java.util.Proper ...

  2. java.util.Properties类 学习笔记

    学习目标:   1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 3.掌握相对路 ...

  3. 【Java笔记】配置文件java.util.Properties类的使用

    配置文件的路径:项目名/src/main/resources/mmall.properties mmall.properties的内容是键值对.例如假设写了ftp服务器的一些信息. ftp.serve ...

  4. 方便好使的java.util.Properties类

    今天偶然碰到这个类,发现jdk中这些平时不大用到的类还挺好玩儿的,用起来也特别实在方便,随便写点记录下. java.util.Properties是对properties这类配置文件的映射.支持key ...

  5. java.util.Properties类的介绍-配置文件的读写【-Z-】

    简介:java.util.Properties是对properties这类配置文件的映射.支持key-value类型和xml类型两种. #打头的是注释行,Properties会忽略注释.允许只有key ...

  6. java.util.Properties类

    http://trans.blog.51cto.com/503170/110227/ http://soft.chinabyte.com/database/395/12625895.shtml

  7. 通过java.util.Properties类来读取.properties文件中key对应的value

    转:http://www.cnblogs.com/panjun-Donet/archive/2009/07/17/1525597.html

  8. Java中Properties类

    1 简介: JDK提供的java.util.Properties类继承自Hashtable类并且实现了Map接口,用map来存储key-value数据,所以存入的数据是无序的.其中键和值都是字符串类型 ...

  9. Java中Properties类的学习总结

    学习目标: 1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 一.认识prope ...

随机推荐

  1. react 渲染

    目录 React渲染 createElement的三个参数 element如何生成真实节点 ReactDOMComponent 作用 ReactCompositeComponentWrapper 作用 ...

  2. Docker(二)Image 与网络

    Docker Image 我们介绍一下如何构造一个自定义的 Docker  Image.在Docker 中,我们使用Dokcerfile 构建一个docker的描述. 首先我们定义一下需要启动一个什么 ...

  3. 2019牛客多校第五场 F maximum clique 1 状压dp+最大独立集

    maximum clique 1 题意 给出一个集合s,求每个子集的最大独立集的权值和(权值是独立集的点个数) 分析 n比较小,一股浓浓的暴力枚举每一个子集的感觉,但是暴力枚举模拟肯定会T,那么想一想 ...

  4. 创建目录命令 - mkdir

    (1) 命令名称:mkdir (2) 英文原意:make directories (3) 命令所在路径:/bin/mkdir (4) 执行权限:所有用户 (5) 功能描述:创建新目录 (6) 语法: ...

  5. Redis Bitmap

    Redis提供对字符串的按位操作,位图把字符串抽象成一个bool类型的数组,可以进行按位操作 比如说我有一个字符串“a” 那他的位图如下 (位) 7 6 5 4 3 2 1 0 (值) ‭0 1 0 ...

  6. sql查询——范围查询(区间查询)

    --范围查询(区间查询) --in() --查询年龄为18,28,38的人 select *from student where age=18 or age=28 or age=38; select ...

  7. 一则关于控制文件全部丢失后如何重新编目RMAN元数据的简单实验

    主题:一则简单的RMAN元数据编目实验,来自于博客园AskScuti. 场景:RMAN备份完整情况下,未使用Catalog目录库.删除了所有的控制文件,在手工重建后,导致记录在控制文件中的RMAN备份 ...

  8. 11g RAC添加用户表空间(数据文件)至文件系统(File System)的修正

    前提:非TEMP.UNDO和SYSTEM表空间,这仨是大爷,您得搂着点.来自博客园AskScuti .客户是添加临时表空间数据文件时,不小心 ADD 到了文件系统中,然后发现,后悔了,还在OS层面 R ...

  9. Hydra暴力破解工具

    hydra [[[-l LOGIN|-L FILE] [-p PASS|-P FILE]] | [-C FILE]] [-e nsr] [-o FILE] [-t TASKS] [-M FILE [- ...

  10. 第四篇,JavaScript面试题汇总

    JavaScript是一种属于网络的脚本语言,已经被广泛用于web实用开发,常用来为网页添加各种各样的动态功能,为用户提供更流畅美观的浏览效果.通常JavaScript脚本是通过嵌入在HTML中来实现 ...