`
雨过天晴0521
  • 浏览: 161068 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

[转]一个保证store内容顺序不变的properties实现

    博客分类:
  • java
 
阅读更多
package com.jianrc.util;

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;

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 &#92;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 &#92;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);
			remove(key);
			commentOrEntrys.add(pe);
		}

		public void remove(String key) {
			for (int i = 0; i < commentOrEntrys.size(); i++) {
				Object obj = commentOrEntrys.get(i);
				if (obj instanceof PropertyEntry) {
					if (obj != null) {
						if (key.equals(((PropertyEntry) obj).getKey())) {
							commentOrEntrys.remove(obj);
						}
					}
				}
			}
		}

		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 string
	 */
	public void addComment(String comment) {
		if (comment != null) {
			context.addCommentLine("#" + comment);
		}
	}

}
分享到:
评论

相关推荐

    excel与properties文件相互转换

    Java中可以使用`java.util.Properties`类的`store()`方法实现 2. **Properties转Excel** - 首先读取Properties文件,解析每行的键值对 - 在Excel中创建一个新的工作表,设置两列,一列作为键,一列作为值 - 使用...

    java修改Properties文件,让输出格式与输入格式保持不变

    然而,当我们读取一个Properties文件并再次保存时,原始的格式可能会发生变化,比如注释丢失、行顺序打乱等。这在某些情况下可能不希望发生,例如当需要保持原始的格式以便于人类阅读或者遵守特定的格式规范时。这篇...

    Java Properties 解决中文乱码和顺序读写.docx

    配置文件通常以`.properties`为扩展名,采用文本格式,每行包含一个键值对,键和值之间以等号(`=`)分隔,注释则以井号(`#`)开头。 Properties 类继承自 Hashtable,因此它拥有字典类的一些基本功能,如添加、删除、...

    Java代码实现对properties文件有序的读写的示例

    Java代码实现对properties文件有序的读写的示例 本篇文章主要介绍了Java代码实现对properties文件...本篇文章提供了一个Java代码实现对properties文件有序的读写的示例,解决了Properties文件读写时元素顺序的问题。

    java实现properties文件读取

    在Java代码中,我们首先创建一个`Properties`对象,它是读取Properties文件的核心工具。 ```java Properties prop = new Properties(); ``` 2. **加载Properties文件**: 使用`InputStream`来读取Properties...

    读取properties返回map并写入文件

    最后,我们通过`store()`方法将Properties对象写入指定的输出文件,同时可以提供一个注释字符串,它会在.properties文件的顶部显示。 总结来说,读取.properties文件并将其内容转化为Map对象,以及将Map对象写回...

    Properties 文件比较工具

    `diffProperties.java`文件很可能是这个工具的主要实现部分,它可能包含了读取两个properties文件,比较其内容并显示差异数目的逻辑。在Java中,我们可以使用`Properties`类的`entrySet()`方法获取所有键值对,然后...

    java 改变Properties文件中的键值

    使用`store()`方法,传入一个`OutputStream`对象,通常是`FileOutputStream`,以及一个可选的评论字符串: ```java FileOutputStream fos = new FileOutputStream("config.properties"); try { props.store(fos,...

    能保存Properties文件注释的Properties工具类

    在Java编程中,Properties类是用于处理属性列表的,这些属性列表通常以键值对的形式存储,例如配置文件。然而,标准的java.util.Properties类在加载和保存文件时会忽略注释,这在某些场景下可能不够理想。针对这个...

    改进java.util.Properties类,让输出格式与输入格式保持不变.

    在Java编程中,`java.util.Properties`类是一个用于处理键值对的标准库,常用于配置文件的读写。然而,该类在加载和保存属性时可能会导致格式的变化,比如默认会将所有字符转换为ASCII,并且在保存时会自动添加行...

    解决Properties写中文乱码

    1. **设置Java程序读写Properties时的编码**:在使用`Properties.load()`和`Properties.store()`方法读写Properties文件时,可以传入一个`java.io.InputStream`或`java.io.OutputStream`对象,并通过`...

    java Properties

    如果需要保持键的顺序,可以使用`LinkedProperties`类,它是`Properties`的一个扩展,保持插入顺序。 通过以上知识点,开发者可以有效地在Java项目中管理和读取`.prop`文件,实现配置信息的灵活存储和访问。在实际...

    java读取properties文件

    在这个例子中,我们创建了一个`FileInputStream`来打开`config.properties`文件,然后通过`Properties`对象的`load()`方法加载文件内容。`getProperty()`方法用于获取特定键对应的值。 2. 处理编码问题: 默认情况...

    java 动态修改Properties,src下或者指定路径

    8. `prop.store(fos, "Update '" + key + "' value")`将修改保存回文件,并添加一个描述性注释。 9. 最后,关闭`fos`以确保所有更改都被写入。 在`main`方法中,获取当前工作目录的路径,拼接上Properties文件的...

    java操作properties方法

    2. **写入Properties文件**:使用`Properties`类的`store()`方法可以将属性列表写入到输出流,例如`writePropertiesFile`方法中的`properties.store(outputStream, comment)`,其中`comment`参数是可选的注释字符串...

    java properties应用案例

    Java Properties是Java语言中用于处理配置文件的一个内置类,它主要负责存储键值对的数据,广泛应用于各种配置文件,如数据库连接配置、系统环境变量设置等。Properties类提供了读取和写入.properties文件的能力,...

    Java源码读写Properties文件.rar

    这段代码首先设置了一个键值对,然后创建一个FileOutputStream对象指向要写入的文件,调用`store()`方法保存Properties对象的内容到文件中。 ### 键值对的操作 除了`getProperty()`和`setProperty()`方法,...

    Properties类小结

    Properties类在Java编程中扮演着重要的角色,它是Java标准库中的一个核心类,主要用于处理配置文件或存储键值对的数据。这个类继承自Dictionary类,并提供了丰富的API来操作属性文件,使得读取、写入配置信息变得...

    properties文件的读取

    创建一个名为`config.properties`的文件,内容如下: ``` username=admin password=123456 database.url=jdbc:mysql://localhost:3306/mydb ``` 2. **加载properties文件** 使用`Properties`类的`load()`...

    解析properties文件demo

    首先,需要创建一个`Properties`对象,然后使用`load()`方法从输入流中加载文件内容。以下是一个简单的例子: ```java Properties props = new Properties(); try (InputStream input = new FileInputStream(...

Global site tag (gtag.js) - Google Analytics