您的位置:首页 > 职场人生

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

2014-02-19 13:18 387 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: