黑马程序员----IO(Properties集合)

package com.mth.Properties;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

/**
 * 
 * @ClassName: PropertiesTest
 * @Description: Properties是 Hashtable的子类 也就是说它具备Map集合的特点 而且它里面的存储的键值对都是字符串
 * 
 *               是集合中和Io技术相结合的集合容器 
 *               该对象特点:可以用于键值对形式的配置文件
 *               那么在加载数据时,需要数据具有固定格式:键=值
 * 
 * 
 * @author mth 75100313@qq.com
 * @date 2014-2-19 上午11:31:34
 * 
 */
public class PropertiesTest {
	// 设置和获取元素
	public static void setAndGet() {

		Properties p = new Properties();
		p.setProperty("zs", "30");
		p.setProperty("ls", "32");
		// 结果{ls=32, zs=30}
		// System.out.println(p);

		// 获取键值对
		Set<String> names = p.stringPropertyNames();
		for (String string : names) {
			String value = p.getProperty(string);
			System.out.println(string + "   " + value);
		}
	}

	// 想要将info.txt中的键值数据存到集合中该如何操作呢?
	/**
	 * 思路:1用一个流和info.txt文件关联 2读取一行数据 将该行数据用"="进行分割 3"="等号左边是键,右边是值,存入到集合即可
	 * 
	 * @throws IOException
	 * 
	 */
	public static void method_1() throws IOException {
		Properties prop = new Properties();
		BufferedReader buffr = new BufferedReader(new FileReader("info.txt"));
		String line = null;
		while ((line = buffr.readLine()) != null) {
			// 独一行以等号切割
			String[] array = line.split("=");
			// 设置集合键值对
			prop.setProperty(array[0], array[1]);
		}
		buffr.close();
		System.out.println(prop);
	}

	/*
	 * void load(InputStream inStream)
	 */
	public static void prpoLoad() throws IOException {
		// 创建与info.txt的文件流
		FileInputStream in = new FileInputStream("info.txt");

		Properties prop = new Properties();
		// 将流中的数据加载记集合
		prop.load(in);

		// System.out.println(prop);

		// 列出集合键值对
		// prop.list(System.out);
		/**
		 * 发现王武(ww)的信息错误 年龄修改为39
		 */
		//改变内存中的数据 info.txt文件里的还没有修改
		prop.setProperty("ww", "39");
		/**
		 * void store(OutputStream out, String comments) 
		 * comments 注释信息 
		 */
		FileOutputStream out=new FileOutputStream("info.txt");
		prop.store(out, "haha");
		
		
		in.close();
		out.close();
		
		
	}

	public static void main(String[] args) throws Exception {
		// setAndGet();
		// method_1();
		prpoLoad();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值