黑马程序员:Java基础总结
集合与IO的结合[Properties类]
集合 Properties
Map 与 IO 的结合
翻译为'特性' :常用于保存程序的配置文件
是hashtable的子类。
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。
是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
那么在加载数据时,需要数据有固定格式:键=值。
修改value方法
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。
是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
那么在加载数据时,需要数据有固定格式:键=值。
与IO交互方法
void | load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。 |
void | store(OutputStream out, String comments) 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。 |
Object | setProperty(String key, String value) 调用 Hashtable 的方法 put 。 |
String | getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。 |
void | list(PrintStream out) 将属性列表输出到指定的输出流。 |
Properties prop =
new
Properties();
FileInputStream fis =
new
FileInputStream(
"info.txt"
);
//将流中的数据加载进集合。
prop.load(fis);
prop.setProperty(
"wangwu"
,
"39"
);
FileOutputStream fos =
new
FileOutputStream(
"info.txt"
);
prop.store(fos,
"haha"
);
// System.out.println(prop);
prop.list(System.
out
);
fos.close();
fis.close();
1,用一个流和info.txt文件关联。
2,读取一行数据,将该行数据用"="进行切割。
3,等号左边作为键,右边作为值。存入到Properties集合中即可。
2,读取一行数据,将该行数据用"="进行切割。
3,等号左边作为键,右边作为值。存入到Properties集合中即可。
public
static
void
method_1()
throws
IOException
{
BufferedReader bufr =
new
BufferedReader(
new
FileReader(
"info.txt"
));
String line =
null
;
Properties prop =
new
Properties();
while
((line=bufr.readLine())!=
null
)
{
String[] arr = line.split(
"="
);
///System.out.println(arr[0]+"...."+arr[1]);
prop.setProperty(arr[0],arr[1]);
}
bufr.close();
System.out.println( prop);
}
// 设置和获取元素。
public
static
void
setAndGet()
{
Properties prop =
new
Properties();
prop.setProperty(
"zhangsan"
,
"30"
);
prop.setProperty(
"lisi"
,
"39"
);
// System.out.println(prop);
String value = prop.getProperty(
"lisi"
);
//System.out.println(value);
prop.setProperty(
"lisi"
,89+
""
);
Set<String> names = prop.stringPropertyNames();
for
(String s : names)
{
System.out.println(s+
":"
+prop.getProperty(s));
}
}
练习:
限制程序运行次数。当运行次数到达5次时,给出,请您注册的提示。并不再让该程序执行。
public
static
void
main(String[] args)
throws
IOException {
Properties path =
new
Properties();
File f =
new
File(
"D:\\count.ini"
);
if
(!f.exists())
// 是否存在
f.createNewFile();
FileInputStream fi =
new
FileInputStream(f);
//因为加载f,会清空,所以放这要加true FileOutputStream fo =
new FileOutputStream(f,
true
);
path.load(fi);
// 读取
int
count = 0;
String value = path.getProperty(
"time"
);
if
(value !=
null
) {
count = Integer. parseInt(value);
if
(count >= 5) {
System.
out
.println(
"试用结束!"
);
return
;
}
}
count++;
path.setProperty(
"time"
, count +
""
);
//必须放到这里,放上面不行了
FileOutputStream fo =
new FileOutputStream(f);
path.store(fo,
""
);
fi.close();
fo.close();
System.
out
.println(
"剩余"
+ (5 - count));
}
自动排列的,其实内部调用了readLine(),spid(),并添加‘=’号,
count.ini 文件
#
#Wed Jul 03 17:41:25 CST 2013
time=1
#Wed Jul 03 17:41:25 CST 2013
time=1