系统的学习 properties对文件的操作,下面贴出代码,其中用问号标注出来的就是暂时没有懂的地方(后面改进),有不足的地方还请指出谢谢,纯手写原创,可以任意转载但请标明出处。
本人的源码分析:https://blog.youkuaiyun.com/qq_26896085/article/details/93977603
package com.origin.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
/**
* @author utsc1243
* @date 2019年5月23日
* 首先properties是继承了hashTable
*/
public class TestProperties {
static Properties properties = new Properties();
public static void main(String[] args) {
InputStream in = TestProperties.class.getClassLoader()
.getResourceAsStream("testproperties.properties");
try {
// load从流对象中读取文件中的数据,
// load源码中通过LineReader读取文件中的每一行数据,处理掉其中的一些特殊的字符,找到key, value
// 最后通过put(key,value)存放在hashTable的键值对中
properties.load(in);
in.close();
// 源码中实际调用的是hashTable中的get(key),获取到value,对value进行处理,返回value或者default
properties.getProperty("test");
// properties继承自hashTable,这里直接调用的是hashTable中的方法
properties.get("test");
// 源码中调用的是getProperty(key), 判断返回值是否为空,为空返回default
properties.getProperty("fdfd", "12345678998");
// 定义输出流对象
// PrintStream out = new PrintStream("D:\\a.txt");
// ????这里为什么不能将数据写入到文件 中去,
// PrintWriter out = new PrintWriter("D:\\a.txt");
// 将读取到的数据写入到指定的文件中去
// properties.list(out);
// 将properties中键值对信息写入到指定的文件中去
// properties.store(out, "describe");
// OutputStream out = new PrintStream("D:\\a.xml");
// 发出表示此表中包含的所有属性的XML文档。
// properties.storeToXML(out, "connectionToXML", "UTF-8");
// 返回properties中的key集合, 源码调用的是hashTable中的keys()
// Enumeration<?> names = properties.propertyNames();
// while (names.hasMoreElements()) {
// System.out.println(names.nextElement());
// }
// setProperty()源码中直接调用hashTable中的put()方法
// properties.setProperty("wangxu", "woodie");
// properties.put("", "");
// 返回key值的set集合,源码中调用 的是hashTable中的keySet()方法
// Set<String> keys = properties.stringPropertyNames();
} catch (IOException e) {
e.printStackTrace();
}
}
}
testproperties.properties文件内容下
test=123456
myname:\ \ \\ = / \ Woodie