更新或添加properties文件(保留存在的properties文件的原有格式)
转载: https://www.cnblogs.com/wangzhisdu/p/7815549.html
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set; /**
* 扩展properties工具类
*
* @author tangming
* @date 2017-11-10
*/
public class SafeProperties { /**
* 内部属性表
*/
private final Properties props; /**
* 保存key与comment的映射, 同时利用这个映射来保证key的顺序。
*/
private final LinkedHashMap<String, String> keyCommentMap = new LinkedHashMap<String, String>(); private static final String BLANK = ""; public SafeProperties() {
super();
props = new Properties();
} public SafeProperties(Properties defaults) {
super();
props = new Properties(defaults);
} /**
* 设置一个属性,如果key已经存在,那么将其对应value值覆盖。
*
* @param key
* @param value
* @return
*/
public String setProperty(String key, String value) {
return setProperty(key, value, BLANK);
} /**
* 设置一个属性,如果key已经存在,那么将其对应value值覆盖。
*
* @param key 键
* @param value 与键对应的值
* @param comment 对键值对的说明
* @return
*/
public synchronized String setProperty(String key, String value, String comment) {
Object oldValue = props.setProperty(key, value);
if (BLANK.equals(comment)) {
if (!keyCommentMap.containsKey(key)) {
keyCommentMap.put(key, comment);
}
} else {
keyCommentMap.put(key, comment);
}
return (String) oldValue;
} /**
* 根据key获取属性表中相应的value。
*
* @param key
* @return
*/
public String getProperty(String key) {
return props.getProperty(key);
} /**
* 根据key获取属性表中相应的value。 如果没找到相应的value,返回defaultValue。
*
* @param key
* @param defaultValue
* @return
*/
public String getProperty(String key, String defaultValue) {
return props.getProperty(key, defaultValue);
} /**
* 从一个字符流中读取属性到属性表中
*
* @param reader
* @throws IOException
*/
public synchronized void load(Reader reader) throws IOException {
load0(new LineReader(reader));
} /**
* 从一个字节流中读取属性到属性表中
*
* @param inStream
* @throws IOException
*/
public synchronized void load(InputStream inStream) throws IOException {
load0(new LineReader(inStream));
} /**
* 从一个字节流中读取属性到属性表中
*
* @param inStream
* @param charset
* @throws IOException
*/
public synchronized void load(InputStream inStream, String charset) throws IOException {
InputStreamReader reader = new InputStreamReader(inStream, charset);
load0(new LineReader(reader));
} /**
* 从一个文件中读取属性到属性表中
*
* @param file 属性文件
* @param charset 字符集
* @throws IOException
*/
public synchronized void load(File file, String charset) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream, charset);
load0(new LineReader(reader));
} /**
* 从一个文件中读取属性到属性表中 默认字符集为utf-8
*
* @param file 属性文件
* @throws IOException
*/
public synchronized void load(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
InputStreamReader reader = new InputStreamReader(inputStream, "utf-8");
load0(new LineReader(reader));
} /**
* 将属性表中的属性写到字符流里面。
*
* @param writer
* @throws IOException
*/
public void store(Writer writer) throws IOException {
store0((writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer), false);
} /**
* 将属性表中的属性写到字节流里面。
*
* @param out
* @throws IOException
*/
public void store(OutputStream out) throws IOException {
store0(new BufferedWriter(new OutputStreamWriter(out, "utf-8")), true);
} /**
* 如果属性表中某个key对应的value值和参数value相同 那么返回true,否则返回false。
*
* @param value
* @return
*/
public boolean containsValue(String value) {
return props.containsValue(value);
} /**
* 如果属性表中存在参数key,返回true,否则返回false。
*
* @param key
* @return
*/
public boolean containsKey(String key) {
return props.containsKey(key);
} /**
* 获取属性表中键值对数量
*
* @return
*/
public int size() {
return props.size();
} /**
* 检查属性表是否为空
*
* @return
*/
public boolean isEmpty() {
return props.isEmpty();
} /**
* 清空属性表
*/
public synchronized void clear() {
props.clear();
keyCommentMap.clear();
} /**
* 获取属性表中所有key的集合。
*
* @return
*/
public Set<String> propertyNames() {
return props.stringPropertyNames();
} public synchronized String toString() {
StringBuffer buffer = new StringBuffer();
Iterator<Map.Entry<String, String>> kvIter = keyCommentMap.entrySet().iterator();
buffer.append("[");
while (kvIter.hasNext()) {
buffer.append("{");
Map.Entry<String, String> entry = kvIter.next();
String key = entry.getKey();
String val = getProperty(key);
String comment = entry.getValue();
buffer.append("key=" + key + ",value=" + val + ",comment=" + comment);
buffer.append("}");
}
buffer.append("]");
return buffer.toString();
} public boolean equals(Object o) {
// 不考虑注释说明是否相同
return props.equals(o);
} public int hashCode() {
return props.hashCode();
} private void load0(LineReader lr) throws IOException {
char[] convtBuf = new char[1024];
int limit;
int keyLen;
int valueStart;
char c;
boolean hasSep;
boolean precedingBackslash;
StringBuffer buffer = new StringBuffer(); while ((limit = lr.readLine()) >= 0) {
c = 0;
keyLen = 0;
valueStart = limit;
hasSep = false;
// 获取注释
c = lr.lineBuf[keyLen];
if (c == '#' || c == '!') {
String comment = loadConvert(lr.lineBuf, 1, limit - 1, convtBuf);
if (buffer.length() > 0) {
buffer.append("\n");
}
buffer.append(comment);
continue;
}
precedingBackslash = false;
while (keyLen < limit) {
c = lr.lineBuf[keyLen];
// need check if escaped.
if ((c == '=' || c == ':') && !precedingBackslash) {
valueStart = keyLen + 1;
hasSep = true;
break;
} else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
valueStart = keyLen + 1;
break;
}
if (c == '\\') {
precedingBackslash = !precedingBackslash;
} else {
precedingBackslash = false;
}
keyLen++;
}
while (valueStart < limit) {
c = lr.lineBuf[valueStart];
if (c != ' ' && c != '\t' && c != '\f') {
if (!hasSep && (c == '=' || c == ':')) {
hasSep = true;
} else {
break;
}
}
valueStart++;
}
String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
setProperty(key, value, buffer.toString());
// reset buffer
buffer = new StringBuffer();
}
} /*
* 基于java.util.Properties.LineReader进行改造
*
* Read in a "logical line" from an InputStream/Reader, skip all comment and blank lines and filter out those leading whitespace characters ( , and ) from the beginning of a "natural line". Method
* returns the char length of the "logical line" and stores the line in "lineBuf".
*/
class LineReader {
public LineReader(InputStream inStream) {
this.inStream = inStream;
inByteBuf = new byte[8192];
} public LineReader(Reader reader) {
this.reader = reader;
inCharBuf = new char[8192];
} byte[] inByteBuf;
char[] inCharBuf;
char[] lineBuf = new char[1024];
int inLimit = 0;
int inOff = 0;
InputStream inStream;
Reader reader; int readLine() throws IOException {
int len = 0;
char c = 0; boolean skipWhiteSpace = true;
boolean isNewLine = true;
boolean appendedLineBegin = false;
boolean precedingBackslash = false;
boolean skipLF = false; while (true) {
if (inOff >= inLimit) {
inLimit = (inStream == null) ? reader.read(inCharBuf) : inStream.read(inByteBuf);
inOff = 0;
if (inLimit <= 0) {
if (len == 0) {
return -1;
}
return len;
}
}
if (inStream != null) {
// The line below is equivalent to calling a
// ISO8859-1 decoder.
c = (char) (0xff & inByteBuf[inOff++]);
} else {
c = inCharBuf[inOff++];
}
if (skipLF) {
skipLF = false;
if (c == '\n') {
continue;
}
}
if (skipWhiteSpace) {
if (c == ' ' || c == '\t' || c == '\f') {
continue;
}
if (!appendedLineBegin && (c == '\r' || c == '\n')) {
continue;
}
skipWhiteSpace = false;
appendedLineBegin = false;
}
if (isNewLine) {
isNewLine = false;
} if (c != '\n' && c != '\r') {
lineBuf[len++] = c;
if (len == lineBuf.length) {
int newLength = lineBuf.length * 2;
if (newLength < 0) {
newLength = Integer.MAX_VALUE;
}
char[] buf = new char[newLength];
System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
lineBuf = buf;
}
// flip the preceding backslash flag
if (c == '\\') {
precedingBackslash = !precedingBackslash;
} else {
precedingBackslash = false;
}
} else {
// reached EOL
if (len == 0) {
isNewLine = true;
skipWhiteSpace = true;
len = 0;
continue;
}
if (inOff >= inLimit) {
inLimit = (inStream == null) ? reader.read(inCharBuf) : inStream.read(inByteBuf);
inOff = 0;
if (inLimit <= 0) {
return len;
}
}
if (precedingBackslash) {
len -= 1;
// skip the leading whitespace characters in following line
skipWhiteSpace = true;
appendedLineBegin = true;
precedingBackslash = false;
if (c == '\r') {
skipLF = true;
}
} else {
return len;
}
}
}
}
} /*
* Converts encoded \uxxxx to unicode chars and changes special saved chars to their original forms
*/
private String loadConvert(char[] in, int off, int len, char[] convtBuf) {
if (convtBuf.length < len) {
int newLen = len * 2;
if (newLen < 0) {
newLen = Integer.MAX_VALUE;
}
convtBuf = new char[newLen];
}
char aChar;
char[] out = convtBuf;
int outLen = 0;
int end = off + len; while (off < end) {
aChar = in[off++];
if (aChar == '\\') {
aChar = in[off++];
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = in[off++];
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.");
}
}
out[outLen++] = (char) value;
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
out[outLen++] = aChar;
}
} else {
out[outLen++] = (char) aChar;
}
}
return new String(out, 0, outLen);
} private void store0(BufferedWriter bw, boolean escUnicode) throws IOException {
synchronized (this) {
Iterator<Map.Entry<String, String>> kvIter = keyCommentMap.entrySet().iterator();
while (kvIter.hasNext()) {
Map.Entry<String, String> entry = kvIter.next();
String key = entry.getKey();
String val = getProperty(key);
String comment = entry.getValue();
key = saveConvert(key, true, escUnicode);
/*
* No need to escape embedded and trailing spaces for value, hence pass false to flag.
*/
val = saveConvert(val, false, escUnicode);
if (!comment.equals(BLANK))
writeComments(bw, comment);
bw.write(key + "=" + val);
bw.newLine();
}
}
bw.flush();
} private static void writeComments(BufferedWriter bw, String comments) throws IOException {
bw.write("#");
int len = comments.length();
int current = 0;
int last = 0;
while (current < len) {
char c = comments.charAt(current);
if (c > '\u00ff' || c == '\n' || c == '\r') {
if (last != current)
bw.write(comments.substring(last, current));
if (c > '\u00ff') {
bw.write(c);
} else {
bw.newLine();
if (c == '\r' && current != len - 1 && comments.charAt(current + 1) == '\n') {
current++;
}
if (current == len - 1
|| (comments.charAt(current + 1) != '#' && comments.charAt(current + 1) != '!'))
bw.write("#");
}
last = current + 1;
}
current++;
}
if (last != current)
bw.write(comments.substring(last, current));
bw.newLine();
} /*
* Converts unicodes to encoded \uxxxx and escapes special characters with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace, boolean escapeUnicode) {
int len = theString.length();
int bufLen = len * 2;
if (bufLen < 0) {
bufLen = Integer.MAX_VALUE;
}
StringBuffer outBuffer = new StringBuffer(bufLen); for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
// Handle common case first, selecting largest block that
// avoids the specials below
if ((aChar > 61) && (aChar < 127)) {
if (aChar == '\\') {
outBuffer.append('\\');
outBuffer.append('\\');
continue;
}
outBuffer.append(aChar);
continue;
}
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
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;
case '=': // Fall through
case ':': // Fall through
case '#': // Fall through
case '!':
outBuffer.append('\\');
outBuffer.append(aChar);
break;
default:
if (((aChar < 0x0020) || (aChar > 0x007e)) & escapeUnicode) {
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 {
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' }; }
测试:
package main.java; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream; public class PropertiesGen { public static void main(String[] args) {
updateProperties("askd.iu.er", "12336");
} public static void updateProperties(String keyname,String keyvalue) {
try {
//Properties props = new Properties();
SafeProperties props = new SafeProperties();
props.load(new FileInputStream("D:/test/cd.properties")); OutputStream fos = new FileOutputStream("D:/test/cd.properties");
props.setProperty(keyname, keyvalue);
props.store(fos);
} catch (IOException e) {
System.err.println("属性文件更新错误");
}
} }
更新或添加properties文件(保留存在的properties文件的原有格式)的更多相关文章
- 3.Git基础-查看当前文件状态、跟踪新文件、暂存文件、忽略文件、提交更新、移除文件、移动文件
1.检查当前文件状态 -- git status git diff git diff --staged git status :我们可以使用 git status 来查看文件所处的状态.当运 ...
- Python中,添加写入数据到已经存在的Excel的xls文件,即打开excel文件,写入新数据
背景 Python中,想要打开已经存在的excel的xls文件,然后在最后新的一行的数据. 折腾过程 1.找到了参考资料: writing to existing workbook using xlw ...
- Maven项目中在properties 中使用 ${} 来引用pom文件中的属性
比如在pom文件中定义了属性如下: <jdbc.host.global>127.0.0.1</jdbc.host.global> <jdbc.databasename.g ...
- applicationContext.xml文件如何调用外部properties等配置文件
只需要在applicationContext.xml文件中添加一行: <!-- 导入外部的properties文件 --> <context:property-placeholder ...
- gen目录无法更新,或者gen目录下的R.JAVA文件无法生成
gen目录无法更新,或者gen目录下的R.JAVA文件无法生成 1.gen目录的用处 android gen目录下的R.java并不是由用户创建,而是android工程本身将android的资源进行自 ...
- 22Spring_JdbcTemplatem模板工具类的使用——使用外部属性文件来配置(properties)
前一篇文章写得是xml文件来配置数据库连接的.但是为了方便,我们实际中采用的是properties文件的方式来配置数据库的.修改properties 文件 会比 修改 xml文件 方便. 做法是: 将 ...
- 【Properties文件】Java使用Properties来读取配置文件
配置文件位置及内容 执行结果 程序代码 package Utils.ConfigFile; import java.io.BufferedInputStream; import java.io.B ...
- 安装Office时出现windows installer服务不能更新一个或多个受保护的windows文件错误的解决方法
今天在Windows XP上安装Microsoft Office 2010时,总是遇到“Windows Installer服务不能更新一个或多个受保护的windows文件,安装失败,正在回滚更改”提示 ...
- 无法为数据库 XXX 中的对象XXX 分配空间,因为 'PRIMARY' 文件组已满。请删除不需要的文件、删除文件组中的对象、将其他文件添加到文件组或为文件组中的现有文件启用自动增长,以便增加可用磁盘空间。
无法为数据库 XXX 中的对象XXX 分配空间,因为 'PRIMARY' 文件组已满.请删除不需要的文件.删除文件组中的对象.将其他文件添加到文件组或为文件组中的现有文件启用自动增长,以便增加可用磁盘 ...
随机推荐
- Solution -「多校联训」取石子游戏
\(\mathcal{Description}\) Link. 有 \(n\) 堆石子,第 \(i\) 堆有 \(x_i\) 个,Alice 每次只能从这堆中拿走 \(a_i\) 个石子,Bo ...
- 关于 Xcode 更新 appleID 更换
可能不少人会遇到 前一位同事走之后,他的 appID帐号下载的东西更新不了 下面给予大家一个解决办法 例如 Xcode 1.打开引用程序目录 2.找到Xcode,右键"显示包内容&quo ...
- 使用第三方插件pagination在页面实现分页功能
1.导入相应的js和css文件 2.在相应的页面映入pagination.js和pagination.css 3.将页面的分页代码替换为pagination动态生成的分页代码 4.编写js代码
- Meterpreter核心命令
实验目的 掌握Meterpreter常见的基本命令的使用 实验原理 1.Meterpreter介绍 meterpreter是metasploit框架中的一个扩展模块,作为溢出成功以后的攻击载荷使用,攻 ...
- RFC2544时延测试——信而泰网络测试仪实操
关键词:RFC2544:时延测试:标记帧:储存转发时延:直通交换时延 时延概述: 时延也常被成为延时(latency),是指一个帧从源点到目的点的总传输时间,包括网络节点的处理时间和在传输介质上的传播 ...
- 如何在win10系统上安装linux子系统
对于软件开发人员来说,linux基本上是一个绕不过去的槛. 因为工作经常要用到linux,电脑用纯linux还是windows + 虚拟机装linux,我一直纠结. 如果装个纯linux,则一些win ...
- [系统安全] 十六.PE文件逆向基础知识(PE解析、PE编辑工具和PE修改)
[系统安全] 十六.PE文件逆向基础知识(PE解析.PE编辑工具和PE修改) 文章来源:https://masterxsec.github.io/2017/05/02/PE%E6%96%87%E4%B ...
- 45个 GIT 经典操作场景,专治不会合代码
大家好,我是小富~ 技术交流关注公众号:程序员内点事 传送门:原文地址 git对于大家应该都不太陌生,熟练使用git已经成为程序员的一项基本技能,尽管在工作中有诸如 Sourcetree这样牛X的客户 ...
- 怎样快速对二进制和十进制进行互转化——IP地址规划与设计总结
转至:https://blog.csdn.net/erlian1992/article/details/47342189 最近一直在看全国计算机三级网络技术这本书,看到第二章的时候,不免会遇到计算机中 ...
- (第三章)TF框架之实现验证码识别
这里实现一个用神经网络(卷积神经网络也可以)实现验证码识别的小案例,主要记录本人做这个案例的流程,不会像之前那么详细,主要用作个人记录用... 这里是验证码的四个字母,被one-hot编码后形成的四个 ...