properties文件的读取和写入

什么是properties文件?

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

Properties文件的读取:

普通读取:利用BufferInputStream缓冲输入流进行读取,可以读取到文件的所有内容,但这样读取失去了properties文件的特点。这种文件是以key=value格式存储内容。

代码实现:

public class Main {
	public static void main(String[] args) {
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:\\IO流\\data.properties"))) {
			int data =  -1;
			while((data = bis.read())!=-1) {
				System.out.print((char)data);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

使用Properties类读取:我们需要使用load()方法将“输入流”加载至Properties集合对象中。这样我们就可以根据key来获取value的值。
代码实现:


public class Main {
	public static void main(String[] args) {
		try ( BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\IO流\\data.properties"))) {
			Properties props = new Properties();
			props.load(bis); //将“输入流”加载至Properties集合对象中
			//根据key,获取value
			System.out.println(props.get("cn"));
			System.out.println(props.get("kr"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 Properties文件的写入:

   首先需要创建一个Properties对象props,使用put()方法将键和值放入Properties集合对象中,然后需要借助输出流通过store()方法把集合中的临时数据,持久化写入到硬盘中存储。

代码实现:

public class Main {
	public static void main(String[] args) {
		//Properties格式文件的写入
		Properties props = new Properties();
		props.put("f1", "2222");
		props.put("f2", "2342");
		//使用输出流,将Properties集合中的KV键值对,写入.properties文件
		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C:\\IO流\\demo.properties"))) {
			props.store(bos, "just do it");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值