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

properties文件的读取和写入

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

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();
		}
	}
}

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

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

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