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 ...
随机推荐
- 安装多个jdk环境7、8、11等,并且切换默认使用版本
背景 在公司开发时,不同项目往往使用不同的jdk.目前使用最多的应该是JDK1.8,但是有些老项目使用1.7甚至1.6等 或者你想学习JDK最新版本,一些新特新如JDK11,现在最新都有JDK13 1 ...
- eclipse中tomcat正常启动,但浏览器访问不了tomcat首页之tomcat配置问题
症状: tomcat在eclipse里面能正常启动,而在浏览器中访问http://localhost:8080/不能访问,且报404错误.同时其他项目页面也不能访问. 关闭eclipse里面的tomc ...
- 【NOIP2011提高组】计算系数
计算系数 算法:真·滚动数组模拟!!! 马上CSP/S了,这是远在今年暑假前的一天的校内考试题中的一道.当时做的时候不会组合数,不会二项式定理,不会DP,不会……只知道应该n*n的空间存一个杨辉三角形 ...
- 如何用python操作XML文件
备注: 基于python3 背景:在统计覆盖率的时候希望绕属性name为test的节点 具体实现源码如下所示,基本都是基于节点属性操作的,当然也就可以基于tag等其他标签去做,可根据需要调整 from ...
- rest_framework:响应器(渲染器)
一.作用: 根据用户的请求url或者用户可接受的类型.筛选出合适的渲染组件 用户请求url: http://127.0.0.1:8000/test/?format=json http://127.0. ...
- SequoiaDB报告创建线程失败的解决办法
1.问题背景 对于分布式数据库和分布式环境,高并发和高性能压力的情况下,出现线程创建失败等等问题也是十分常见的,这时候就十分考虑数据库管理员的经验,需要能快速的定位到问题和瓶颈所在,快速解决.本文也是 ...
- Vue项目接入MQTT
Vue项目接入MQTT 安装mqtt库 npm install mqtt --save Vue代码实现 <template> <div id="app"> ...
- c#中转义字符\n和\r的区别
在c#中\n代表换行,\r代表回车,但\r是把后面的字符覆盖前面的,例: "1234\n567" 输出的是 1234 567 "1234\r567"输出的是 5 ...
- Oracle VM VirtualBox - ping不通虚拟机
问题描述 用Oracle VM VirtualBox创建虚拟机后,本机电脑ping不通虚拟机 解决方案 https://www.cnblogs.com/ranrongzhen/p/6958485.ht ...
- Python之旅第二天(第一天补充部分、数据类型、运算逻辑、部分方法的引入、pycharm)
今天其实是有点小忙的,但是干自己不喜欢事情的结果就是,要睡觉了都不知道自己在忙鸡毛,所以还是不继续想了,脑仁疼.回忆一下今天的学习内容,着实有点少,本大侠还没怎么过瘾呢.废话不多说. while补充两 ...