Properties类
Properties是hashtable的子类。是个Map集合
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串。是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
那么在加载数据时,需要数据有固定格式:键=值。
Properties,该类主要用于读取以项目的配置文件(以.properties结尾的文件和.xml文件)。
properties文件
1、properties文件是一个文本文件2、properties文件的语法有两种,一种是注释,一种属性配置。
注 释:前面加上#号
属性配置:以“键=值”的方式书写一个属性的配置信息。
3、properties文件的一个属性配置信息值可以换行,但键不可以换行。值换行用“\”表示。
4、properties的属性配置键值前后的空格在解析时候会被忽略。
5、properties文件可以只有键而没有值。也可以仅有键和等号而没有值,但无论如何一个属性配置不能没有键。
设置和获取元素:
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));
}
}
读取文件中的键值:
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 loadDemo()throws IOException
{
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();
}
用于记录应用程序运行次数。
如果使用次数已到,那么给出注册提示。
import java.io.*;
import java.util.*;
class RunCount
{
public static void main(String[] args) throws IOException
{
Properties prop = new Properties();
File file = new File("count.ini");
if(!file.exists())
file.createNewFile();
FileInputStream fis = new FileInputStream(file);
prop.load(fis);
int count = 0;
String value = prop.getProperty("time");
if(value!=null)
{
count = Integer.parseInt(value);
if(count>=5)
{
System.out.println("您好,使用次数已到,拿钱!");
return ;
}
}
count++;
prop.setProperty("time",count+"");
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos,"");
fos.close();
fis.close();
}
dom4j 是一个Java的XML API,类似于jdom,用来读写XML文件的。