1.1.2.6
Properties类
Properties是HashTable的子类。增加了将hashtable对象中的关键字和值保存到文件以及从文件中读取关键字和值到hashtable对象中的方法。
如果要用properties.store()方法存储properties中的内容,每个属性的关键字和值都必须是string类型。
编程举例:使用properties把程序的启动运行次数记录在文件里,每次运行时打印出它的运行次数。
import java.util.*; //Properties在这个包中
import java.io.*; //fileinputstream和fileoutputstream在这个包中
public class PropertiesFile
{
public static void main(String[] args)
{
Properties settings=new Properties();
try
{
settings.load(new FileInputStream("count.txt")); //从文件"count.txt"装载
}
catch(Exception e)
{
settings.setProperty("count",String.valueOf(0));
//发生异常,说明第一次运行,第一次运行时还不存在文件“count.txt”,我们只能不从文件中取,而设置它的默认值为0
}
int count=Integer.parseInt(settings.getProperty("count"))+1;
/*
本来可以使用从hashtable中继承的get方法,但是由于我们处理的是字符串,所以使用这个方法,
但由于返回的是字符串,所以转换成整数,由于存的是到上一次为止的运行次数,所以要加一。
*/
System.out.println("这是第"+count+"次运行!");
settings.setProperty("count",new Integer(count).toString());
/*
将次数存入property对象中,由于存入的是字符串,所以要转换成字符串。
*/
try
{
settings.store(new FileOutputStream("count.txt"),"program is used:");
//发生异常,说明第一次运行,这时会创建一个文件。
/*
将property对象中的结果存入文件,第一个参数为文件,第二个参数为标题。
*/
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
1.1.2.7 读取Properties文件六种方法
1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);
2。使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());
3。使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);
4。使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);
6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);
补充
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);
---
---
主要类与方法和描述
1.
load() //从一个外部流读取属性
2.
store() //将属性保存到外部流(特别是文件)
3.
getProperty() //取得一个指定的属性
4.
setProperty() //设置一个指定的属性
5.
list() //列出这个Properties对象包含的全部“key-value”对
6.
System.getProperties() //取得系统当前的环境变量
你可以这样保存一个properties文件:
1.
Properties prop = new Properties();
2.
prop.setProperty("key1", "value1");
3.
...
4.
FileOutputStream out = new FileOutputStream("config.properties");
5.
prop.store(out, "--这里是文件头,可以加入注释--");