Properties对象是之前Map集合下Hashtable中的子类,那么它也就拥有集合的一些特性,所以可以将文件进行集合式的写入和读取,但是键和值都仅限于字符串形式,通常该集合用于操作以键值对形式存在的配置文件。
例如:
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo {
/**
* @param args
* @author kk
* @throws Exception
*
*/
public static void main(String[] args) throws Exception {
/*
* Map
* |--Hashtable
* |--Properties:
*/
propertiesDemo_4();
}
public static void propertiesDemo_4() {
Properties p = new Properties();
//集合中的数据如果来自于一个文件。
//注意:必须要保证该文件中的数据是键值对。
//需要使用到读取流。
}
public static void propertiesDemo_3() throws IOException {
Properties p = new Properties();
//存储元素。
p.setProperty("lisi", "24");
p.setProperty("zhangsan", "23");
p.setProperty("zhaoliu", "26");
p.setProperty("wangwu", "25");
//想要把这些集合中的字符串键值信息持久化存储到文件中,就需要并联输出流
FileOutputStream fos = new FileOutputStream("info.txt");
//将集合数据存储到文件中,使用store方法。
p.store(fos, "name+age");//不建议使用中文
fos.close();
}
/*
* 演示:Properties集合和流对象相结合的功能
*/
public static void propertiesDemo_2() {
Properties p = new Properties();
p.setProperty("李四", "24");
p.setProperty("张三", "23");
p.setProperty("赵六", "26");
p.setProperty("王五", "25");
p.list(System.out);
System.out.println(p);
}
/*
* Properties集合的存和取。
*/
public static void propertiesDemo() {
//创建一个Properties集合。
Properties prop = new Properties();
//存储元素。
prop.setProperty("1", "zhangsan");
prop.setProperty("4", "lisi");
prop.setProperty("3", "wangwu");
prop.setProperty("2", "zhaoliu");
//修改元素
prop.setProperty("2", "李四");
//取出所有元素。
Set<String> names = prop.stringPropertyNames();
for(String name:names){
String value = prop.getProperty(name);
System.out.println(name+"="+value);
}
}
}
那么完整的结合之后如下所示:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesText {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
getAppCount();
}
public static void getAppCount() throws IOException {
//将配置文件封装成File对象
File confile = new File("count.properties");
if(!confile.exists()){
confile.createNewFile();
}
FileInputStream fis = new FileInputStream(confile);
Properties prop = new Properties();
prop.load(fis);
//从集合中通过键获取次数
String value = prop.getProperty("time");
//定义计数器,记录获取到的次数
int count = 0;
if(value!=null){
count = Integer.parseInt(value);
if (count>5) {
throw new RuntimeException("您的使用次数超过限制,请注册购买!");
}
}
count++;
//将改变后的次数重新存储到集合中
prop.setProperty("time", count+"");
FileOutputStream fos = new FileOutputStream(confile);
prop.store(fos, "");
fos.close();
fis.close();
}
}
这几天智言也在重新复习之前的一些基础知识,所以中间隔了几天没有文章。
智言个人博客







评论前必须登录!
注册