Java Properties类 按输入顺序输出,每条添加注释

本文介绍如何使用Java Properties类按照输入顺序输出属性,并为每条属性添加注释。作者发现标准Properties类在输出时顺序不固定,于是自定义了一个解决方案,经过测试能够实现预期效果。

    今天想把输入Property类的信息,输出看一下,输出之后发现顺序是乱的,后来看了代码才明白怎么回事,于是决定自己瞎写一个,经测试还能用。望各位大神观摩指导。。。。

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Properties;

/**
 * This class is to provide function output properties by input order and add comment to each property.
 * @author zhengfan1
 */
public class OutputOrderProperties extends Properties
{

	private LinkedHashMap<String, String> commentMap = new LinkedHashMap<String,String>();
	
	/**
	 * Version ID
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Constructor.
	 */
	public OutputOrderProperties()
	{
		super();
	}
	
	/**
	 * Constructor.
	 * @param properties
	 * 		the java propertis.
	 */
	public OutputOrderProperties(Properties properties)
	{
		super(properties);
		//Initialize the comment.
		Iterator<Object> iterator = properties.keySet().iterator();
		while(iterator.hasNext())
		{
			Object key = iterator.next();
			this.commentMap.put((String) key, null);
		}
	}
	
	/**
	 * Add comment to a property.
	 * @param key
	 * 		the key of the property.
	 * @param comment
	 * 		the comment of the property.
	 * @return
	 * 		true => add it
	 * 		false => don't have this key.
	 */
	public boolean addComment(String key , String comment)
	{
		if(this.contains(key))
		{
			this.commentMap.put(key, comment);
			return true;
		}
		return false;
	}
	
	/**
	 * To set property.
	 * @param key
	 * 		the key of property.
	 * @param value
	 * 		the value of property.
	 * @param comment
	 * 		the comment of property.
	 */
	public void setP(String key , String value , String comment)
	{
		this.commentMap.put(key, comment);
		this.setProperty(key, value);
	}
	
	/**
	 * To output according to the order of input.
	 * @param writer
	 * 		the writer
	 * @param comments
	 * 		the comments of this property file.
	 * @throws IOException
	 * 		exception.
	 */
	public void orderStore(Writer writer , String comments) throws IOException
	{
		BufferedWriter bufferedWriter = (writer instanceof BufferedWriter) ? (BufferedWriter)writer : new BufferedWriter(writer);
		if (comments != null) 
		{
			OutputOrderProperties.writeComments(bufferedWriter, comments);
	    }
	    bufferedWriter.write("#" + new Date().toString());
	    bufferedWriter.newLine();
	    bufferedWriter.newLine();
	    
	    synchronized (this) 
	    {
	    	Iterator<String> iterator = this.commentMap.keySet().iterator();
	    	while(iterator.hasNext())
	    	{
	    		String key = iterator.next();
	    		String value = this.getProperty(key);
	    		String comment = this.commentMap.get(key);
	    		key = saveConvert(key, true, false);
		        value = saveConvert(value, false, false);
	    		key = saveConvert(key, true, false);
	    		if(comment != null && ! comment.equals(""))
	    		{
	    			writeComments(bufferedWriter, comment);
	    		}
	    		bufferedWriter.write(key+"="+value);
	    		bufferedWriter.newLine();
	    		bufferedWriter.newLine();
	    	}
         }
	    bufferedWriter.flush();    
	}
	
	 /*
     * Converts unicodes to encoded \uxxxx and escapes
     * special characters with a preceding slash
     * !!! Copy from java source code.
     */
    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();
    }
	
    /*
     * !!!Copy from java source code.
     */
	private static void writeComments(BufferedWriter bw, String comments) 
	        throws IOException {
	        bw.write("#");
	        int len = comments.length();  
	        int current = 0;
	        int last = 0;
	        char[] uu = new char[6];
	        uu[0] = '\\';
	        uu[1] = 'u';
	        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') {
	                    uu[2] = toHex((c >> 12) & 0xf);
	                    uu[3] = toHex((c >>  8) & 0xf);
	                    uu[4] = toHex((c >>  4) & 0xf);
	                    uu[5] = toHex( c        & 0xf);
	                    bw.write(new String(uu));
	                } 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();
	    }
	
	/*
	 * !!! Copy from java source code.
	 */
	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'
	    };
	
	
}

主要是实现两个功能:

1.顺序输出:

    用户通过使用方法setP来插入数据,三个参数分别为key,value,和comment。之后通过orderStore来输出内容。

2.为每条属性添加注释

    通过setP方法添加的属性都会有注释参数。如果只想使用注释这个功能,可以通过java的Properties类来构造此类对象,之后通过addComment方法来为想要添加的属性添加注释



测试程序:

public static void main(String[] args) throws IOException 
	{
		OutputOrderProperties properties = new OutputOrderProperties();
		FileOutputStream fileOutputStream = new FileOutputStream("test.properties");
		OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream);
		for(int i=0 ; i<10; i++)
		{
			String string = String.valueOf(i);
			properties.setP("Name"+string, string, "the name of "+string);
		}
		properties.orderStore(writer, "This is a test process...");
	}


结果:

#This is a test process...
#Wed Mar 13 15:34:03 CST 2013

#the name of 0
Name0=0

#the name of 1
Name1=1

#the name of 2
Name2=2

#the name of 3
Name3=3

#the name of 4
Name4=4

#the name of 5
Name5=5

#the name of 6
Name6=6

#the name of 7
Name7=7

#the name of 8
Name8=8

#the name of 9
Name9=9


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值