黑马程序员技术交流社区
标题:
IO part4
[打印本页]
作者:
fmi110
时间:
2015-8-10 11:48
标题:
IO part4
IO
IO与集合结合的类: Properties
Map
|-- Hashtable
|--Properties
Properties 该集合已限制键值对是 String 类型,所以不需要泛型
常用方法:
Object setProperty(String key,String value); 设置(修改)键值对
返回值是 Hashtable 调用 put 的结果: 此哈希表中指定键的以前的值,如果不存在该值,则返回 null
String getProperty(key);获取key对应的值
Set<String> stringPropertyNames(); 返回列表的键值
void list(PrintStream out); 将属性列表输出至指定流
void list(PrintWriter out); 将属性列表输出至指定流
例: list(System.out);输出至控制台
list(new PrintStream("1.txt"); 输出至文档1.
void load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。
void load(Reader reader)
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)
注意:键值对应该有固定的格式, 键 = 值
void store(OutputStream out, String comments)
以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。
void store(Writer writer, String comments)
以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
*********************************************************************************
练习:记录一个程序运行的次数,当到达次数时,该程序不可以再次运行。
import java.io.*;
import java.util.*;
class MyPropertiesDemo
{
public static void main(String[] args) throws IOException
{
//记录次数
int time = 0;
//创建流关联配置文件
File file = new File("prop.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fin = new FileInputStream(file);
FileOutputStream fos = null;
//创建集合
Properties prop = new Properties();
//加载配置键值对
prop.load(fin);
//查询已用次数
String count = prop.getProperty("time");
if(count==null)
{
count = "0";
}
time = Integer.parseInt(count);
time++;
if(time>=5)
{
System.out.println("Time has reached 5.Use limitied,please register!!");
return;
}
//回传配置信息并存储
count =new Integer(time).toString();
prop.setProperty("time",count);
fos = new FileOutputStream(file);
prop.store(fos,"");
fin.close();
System.out.println("This is the "+time+" time!");
System.out.println("Hello World!");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2