Properties文件的读取与保存

首先,我们要知道properties文件是一种以key=value的格式进行存储内容的。而java中也有Properties类。

我们先创建一个properties格式的文件,命名为data.properties,其内容如下:

yx = 88
zwd = 135
hyz = 180

然后,我们就可以对其进行读取。

		// Properties格式文件的读取
		// 创建输入流
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\io\\data.properties"))) {
			Properties props = new Properties();
			
			props.load(bis); // 将"输入流"加载至Properties集合对象中
			
			// 根据key,获取value
			System.out.println(props.get("yx"));
			System.out.println(props.get("zwd"));
			System.out.println(props.get("hyz"));
			System.out.println(props);
			
		} catch (IOException e) {
			e.printStackTrace();
		}

同时,Properties类也提供了store()方法,可以将注解也加入其中。

		// Properties格式文件写入
		try {
			Properties props = new Properties();
			props.put("whh", "150");
			props.put("lyf", "130");
			props.put("ljc", "120");
			props.put("hwh", "100");
			props.put("wzb", "160");
			
			// 使用"输出流",将Properties集合中的KV键值对,写入*.properties文件
			try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\io\\demo.properties"))){
					props.store(bos, "just do IT");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

我们也可以通过class path读取相对路径下的文件。

        // 通过class path读取相对路径下的文件
		// class path :当前项目编译后的bin目录
		
		// data.properties文件保存在 class path 根目录
		// InputStream in = Demo04.class.getResourceAsStream("/data.properties")
		
		// temp.properties文件保存在 class path 根目录下的com\zwd\demo\目录中
		try (InputStream in = Demo04.class.getResourceAsStream("/com/zwd/demo/temp.properties")){
			
			// 加载读取
			Properties props = new Properties();
			props.load(in);
			
			System.out.println(props);
		} catch (IOException e) {
			e.printStackTrace();
		}

从class path读取文件就可以避免不同环境下文件路径不一致的问题:如果我们把data.properties文件放到class path中,就不用关心它的实际存放路径。在classpath 中的资源文件,路径总是以"\"开头,我们先获取当前的Class 对象,然后调用getResourceAsstream()就可以直接从classpath读取任意的资源文件。

在此我们要注意:在调用getResourceAsstream() 时,如果资源文件不存在,它将返回null 。因此,我们需要检查返回的Inputstream 否为null,如果为null,示资源文件在classpath中没有找到。
 

        try (InputStream input = getClass().getResourceAsStream("/data.properties")) {
            if (input != null) {
                
            }
        }

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值