首页 > 编程语言 > 详细

JDK源码学习(9)- java.util.Properties实例与源码

时间:2016-07-29 19:30:36      阅读:255      评论:0      收藏:0      [点我收藏+]
  1. java.util.Properties说明。

该类主要是读取属性配置文件,两种文件类型:普通文件格式为key = value;xml文件。

1)key = value示例如下:

public class TestProperties {

	public static void main(String[] args) {
		Properties properties = new Properties();
		FileInputStream fileInputStream;
		try {
			fileInputStream = new FileInputStream(new File("D:/testProperties.txt"));
//			properties.loadFromXML(fileInputStream);
			properties.load(fileInputStream);
			for (Object pro : properties.keySet()) {
				System.out.println(pro + "==" + properties.get(pro));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}

配置文件为:

name = hello
value = good

结果为:

name==hello
value==good

2)读取xml文件,代码如下:

public class TestProperties {

	public static void main(String[] args) {
		Properties properties = new Properties();
		FileInputStream fileInputStream;
		try {
			fileInputStream = new FileInputStream(new File("D:/testProperties.xml"));
			properties.loadFromXML(fileInputStream);
//			properties.load(fileInputStream);
			for (Object pro : properties.keySet()) {
				System.out.println(pro + "==" + properties.get(pro));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

配置文件为:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Hi</comment>
<entry key="foo">bar</entry>
<entry key="fu">baz</entry>
<entry key="feee">baeee</entry>
</properties>

运行结果为:

feee==baeee
fu==baz
foo==bar

2.源码分析:

该类继承自HashTable,结构为key-value,如下:

public class Properties extends Hashtable<Object,Object>

1)load(InputStream)方法,该方法主要作用是读取配置文件内的相关配置,并且将信息用key-value结构存放到Properties中。源码为:

  public synchronized void load(InputStream inStream) throws IOException {
        load0(new LineReader(inStream));
    }
private void load0 (LineReader lr) throws IOException {
        char[] convtBuf = new char[1024];
        int limit;
        int keyLen;
        int valueStart;
        char c;
        boolean hasSep;
        boolean precedingBackslash;
        //1.按行读取配置文件,返回值为该行的长度
        while ((limit = lr.readLine()) >= 0) {
            c = 0;
            keyLen = 0;
            valueStart = limit;
            hasSep = false;

            //System.out.println("line=<" + new String(lineBuf, 0, limit) + ">");
            precedingBackslash = false;
            //1.1对该行每个字符进行遍历,找到=或者:符号的位置
            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++;
            }
            //keyLen为符号之前不为空的最终位置,valueStart为符号之后的第一个不为空的位置
            String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
            String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
            //将解析出的key和value存放到hashTable中
            put(key, value);
        }
    }

2)store(OutputStream out, String comments)方法,out为输出的文档,comments为配置文件的说明,在key-value时为注释信息,在xml文件格式下为<comments>标签内容。源代码如下:

 public void store(OutputStream out, String comments)
        throws IOException
    {
        store0(new BufferedWriter(new OutputStreamWriter(out, "8859_1")),
               comments,
               true);
    }

    private void store0(BufferedWriter bw, String comments, boolean escUnicode)
        throws IOException
    {
        if (comments != null) {
            writeComments(bw, comments);
        }
        bw.write("#" + new Date().toString());
        bw.newLine();
        synchronized (this) {
            for (Enumeration<?> e = keys(); e.hasMoreElements();) {
                String key = (String)e.nextElement();
                String val = (String)get(key);
                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);
                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;
        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();
    }


JDK源码学习(9)- java.util.Properties实例与源码

原文:http://yinyueml.blog.51cto.com/4841237/1831684

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!