Properties类的使用和源码浅析

本文详细探讨了Properties类在Java中的作用,包括其内部实现、关键方法的源码解析以及如何在不同位置读取properties文件。通过实例演示,帮助开发者熟练掌握Properties类的使用。

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

 

        Properties类代表持久化属性集合。Properties能够保存到流中,也可以从流中加载。而每一个key和它对应的value在属性列表中用string来表示。

      一、类的继承关系

            

             从继承关系图中可以知道Properties的内部是有Hashtable实现的。

     二、部分方法的源码

                          load(InputStram)

                 

                load0

         

         setProperty(String,String)

         

          getProperty(String)

 

           三、内部类

          

          四、使用Properties读取Java项目不同位置的properties文件

           

                  

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;

public class PropertiesTest
{
	public static void main(String[] args) throws IOException
	{
		//1.读取项目下的properties文件
		//File file = new File("test.properties");
		
		//2.读入项目下新建文件夹中的properties文件
		//File file = new File("lib/test.properties");
		
		//3.读取src下的properties文件
		//File file = new File("src/test.properties");
		
		//4.读取package下面的properties文件,采用类加载
		String path = PropertiesTest.class.getClassLoader().getResource("com/test/px/test.properties").getPath();
		File file = new File(path);
		
		InputStream inStream = new FileInputStream(file);
		
		Properties props = new Properties();
		
		props.load(inStream);
		
		for(Entry<Object, Object> entry: props.entrySet())
		{
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			System.out.println(key+" = "+value);
		}
		
	}
}


 

              
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值