java.util.Properties类,保存时保留注释及格式不变
原文地址: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类,保存时保留注释及格式不变的更多相关文章
- 使用java.util.Properties类读写配置文件
J2SE 1.5 以前的版本要求直接使用 XML 解析器来装载配置文件并存储设置,虽说也并非难事,相比 java.util.Properties却要做额外的解析工作.而java.util.Proper ...
- java.util.Properties类 学习笔记
学习目标: 1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 3.掌握相对路 ...
- 【Java笔记】配置文件java.util.Properties类的使用
配置文件的路径:项目名/src/main/resources/mmall.properties mmall.properties的内容是键值对.例如假设写了ftp服务器的一些信息. ftp.serve ...
- 方便好使的java.util.Properties类
今天偶然碰到这个类,发现jdk中这些平时不大用到的类还挺好玩儿的,用起来也特别实在方便,随便写点记录下. java.util.Properties是对properties这类配置文件的映射.支持key ...
- java.util.Properties类的介绍-配置文件的读写【-Z-】
简介:java.util.Properties是对properties这类配置文件的映射.支持key-value类型和xml类型两种. #打头的是注释行,Properties会忽略注释.允许只有key ...
- java.util.Properties类
http://trans.blog.51cto.com/503170/110227/ http://soft.chinabyte.com/database/395/12625895.shtml
- 通过java.util.Properties类来读取.properties文件中key对应的value
转:http://www.cnblogs.com/panjun-Donet/archive/2009/07/17/1525597.html
- Java中Properties类
1 简介: JDK提供的java.util.Properties类继承自Hashtable类并且实现了Map接口,用map来存储key-value数据,所以存入的数据是无序的.其中键和值都是字符串类型 ...
- Java中Properties类的学习总结
学习目标: 1.认识properties文件,理解其含义,会正确创建properties文件. 2.会使用java.util.Properties类来操作properties文件. 一.认识prope ...
随机推荐
- jdbc中SQL语句拼接java变量
例如:String sql = "select * from user where username='" + username + "' and password =' ...
- 怎么把apk文件部署在云服务器上
你服务器直接使用nginx,将请求映射到固定目录,把你的apk放到该目录.其他都不用干了.
- 2019牛客多校第七场 F Energy stones 树状数组+算贡献转化模拟
Energy stones 题意 有n块石头,每块有初始能量E[i],每秒石头会增长能量L[i],石头的能量上限是C[i],现有m次时刻,每次会把[s[i],t[i]]的石头的能量吸干,问最后得到了多 ...
- 怎么编写API和或者自己不属于知识小案例demo程序
再使用一个函数,进行测试的调用,然后进行调用这样就不需要再为makefile什么,还有就是改什么鬼东西烦恼了. 然后把需要的功能进行分解就行了.
- Android 验证APK签名对比
最近OTT制定产品,其中有一条需求是只能安装自己公司签名的APK,所以在网上找了相关资料,最后总结功能实现如下: 1.签名错误码frameworks/base/core/java/android/co ...
- 大数据-Storm
Storm 流式处理框架 Storm是实时的,分布式,高容错的计算系统.java+cljoure Storm常驻内存,数据在内存中处理不经过磁盘,数据通过网络传输. 底层java+cljoure构成, ...
- 本地cmd连接远程mysql数据库
一.登录远程mysql 输入mysql -h要远程的IP地址 -u设置的MySQL用户名 -p登录用户密码 例如:mysql -h 192.168.1.139 -u root -p dorlocald ...
- js splice()
//arrayObject.splice(index,howmany,item1,.....,itemX) 语法 //测试代码let array;array = ['George','John','T ...
- Oracle中行转列,列转行pivot的用法
测试数据准备 --建表 --drop table SalesList; create table SalesList( keHu ), --客户 shangPin ), --商品名称 salesNum ...
- 【13】堆排序 最小K个数
题目 输入整数数组 arr ,找出其中最小的 k 个数.例如,输入4.5.1.6.2.7.3.8这8个数字,则最小的4个数字是1.2.3.4. 收获 优先队列实现 (n1,n2)->n2-n1是 ...