Properties集合:
Properties类表示一组持久的属性。 Properties可以保存到流中或从流中加载。 属性列表中的每个键及其对应的值都是一个字符串。
特点:
①hashtable的子类,键和值都是String类型,线程安全的
②可以和IO技术相结合
③通常该集合用于操作以键值对存在的配置文件
用法举例
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import java.util.Set;
public class Propertiesdemo {
public static void main(String []args) throws IOException
{
method4();
}
private static void method4() throws IOException {
/*功能:对一个APP的使用次数进行记录,如果打开了五次,就不能打开
* 需要注册
*
* 思想:我们需要一个持久性的文件来进行计数(断电时,仍然能用)
* 这是我们想到需要存储到硬盘来记录计数的次数
* properties类可以和IO技术相结合,把计数的次数存储到硬盘上
* 在程序启动时,首先读取存储次数的配置文件获取次数,并判断是否达到使用次数上限,若达到打
* 印提示信息,若没达到次数加1,再次写入到配置文件中。
*
*/
File ff=new File("count.txt");
if(!ff.exists())
ff.createNewFile();
FileInputStream fs=new FileInputStream(ff);
Properties pt=new Properties();
pt.load(fs);
String value=pt.getProperty("time");
int count=0;
if(value!=null)
{
count=Integer.parseInt(value);
}
count++;
pt.setProperty("time",count+"");
FileOutputStream fs1=new FileOutputStream(ff);
pt.store(fs1, "newdata");
fs.close();
fs1.close();
}
private static void method3() throws IOException {
/*
* 功能:对配置文件中的值进行更改
*/
Properties pt=new Properties();
File file=new File("Propertiesdemo2.txt");
if(!file.exists())
file.createNewFile();
FileInputStream is=new FileInputStream(file);
pt.load(is);
pt.setProperty("price", "2500000");
FileOutputStream os=new FileOutputStream(file);//记住os不能放到前面
//创建文件输出流以写入由指定的File对象表示的文件。 创建一个新的FileDescriptor对象来表示此文件连接。
//会覆盖原文件。
pt.store(os, "car");
}
private static void method2() throws IOException {
/*
* 功能:把内存中的数据通过IO技术写到磁盘上
* 思想:Properties的store方法可以与输出流相关联
* 将此Properties表中的此属性列表(键和元素对)以适合使用load(Reader)方法的格式写入输出字符流。
* 步骤:①创建一个与文件相关联的输出流
* ②用store方法写入到输出流中
*/
Properties pt=new Properties();
pt.setProperty("liu", "18");
pt.setProperty("wang", "18");
pt.setProperty("lily", "18");
pt.setProperty("ni", "18");
OutputStream os=new FileOutputStream("Propertieddemo1.txt");
pt.store(os, "name+age");
}
private static void method1() throws IOException {
/*
* 功能:把磁盘中的数据读取到内存中
* 思路:Properties的load方法可以与输出流相关联
* 从输入字节流读取属性列表(键和元素对)存到内存中。
* list(PrintStream o) 将此属性列表打印到指定的输出流。
* 步骤:①创建一个输入流对象并与配置信息文件相关联
* ②通过load方法读取文件中的信息写入到内存中
*/
File f=new File("Propertiesdemo.txt");
Properties pt=new Properties();
FileInputStream fs=new FileInputStream(f);
pt.load(fs);
pt.list(System.out);
/*Set<String> st=pt.stringPropertyNames();
for(String str:st)
{
if(str.startsWith("#"))//健壮性判断
continue;
String value=pt.getProperty(str);
System.out.println(str+"="+value);
}*/
}
}