栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

properties文件的读取和写入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

properties文件的读取和写入

目录

一、properties文件的读取

二、properties文件的写入


properties文件是一种属性文件,这种文件以key=value(键值对)格式存储内容。Java中可以使用Properties类来读取这个文件,使用Properties类中的getProperties(key)方法来得到对应的数据。一般properties文件作为一些参数的存储,使得代码更加灵活。

一、properties文件的读取

(1)使用BufferedInputStream(缓冲输入流)创建输入流进行读取,读取后以key=value(键值对)格式存储数据。

代码实现:

 //Properties格式文件的读取
	//创建输入流
	try (
	 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\student\aaa.properties"))) {
		
		int data =-1;
		while((data=bis.read())!=-1) {
			System.out.print((char)data);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	//运行结果
	//k=12
    //b=34
	//c=11

(2)使用Properties类中的load()方法读取,将“输入流”加载到Properties集合对象中,根据key来获取value的值

代码实现:

try (
	 BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\student\aaa.properties"))) {
		Properties props=new Properties();
		  props.load(bis);//将“输入流”加载到Properties集合对象中
		       //根据key,获取value
				System.out.println(props.get("k"));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	//运行结果
	//12
二、properties文件的写入

因为properties文件数据是以集合形式存储,所以可以用put()方法将KV键值对存入Properties集合中,再通过输出流使用store()方法将集合中的临时数据,持久化写入硬盘中存储。

//properties格式文件的写入
	try{
		Properties props=new Properties();
		props.put("Q", "123");
		props.put("W", "432");
		props.put("E", "986");
		props.put("R", "457");
	
	//使用“输出流”,将properties集合中的KV键值对,写入*.properties文件
	  try (BufferedOutputStream bos = new BufferedOutputStream(
			new FileOutputStream("D:\student\bbb.properties"))) {
		props.store(bos, "just do IT");
	  }
	} catch (IOException e) {
		
		e.printStackTrace();
	}
	

//运行结果
//	#just do IT
//	#Wed Jun 01 00:14:57 CST 2022
//	W=432
//	R=457
//	Q=123
//	E=986

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/943234.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号