java.util.Properties方法系统学习

本文深入解析Java中Properties类的使用方法,包括加载配置文件、读取属性、写入属性及处理异常等关键步骤。通过实例代码,展示了如何利用Properties类进行文件读写,以及其内部实现机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

系统的学习 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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值