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();
}
}
}
相关文章
- 使用DBeaver连接Phoenix异常Inconsistent namespace mapping properties. Cannot initiate connection as SYSTEM:CATALOG is found but client does not have phoenix.schema.isNamespaceMappingEnabled enabled
- [Spring Boot] Set Context path for application in application.properties
- [React] React Fundamentals: Accessing Child Properties
- 将properties文件放在Jar包并读取
- intellij idea里Properties中文unicode显示问题
- [Javascript] Customize Behavior when Accessing Properties with Proxy Handlers
- loadrunner12.55 :HTTP Properties > Advanced设置 之 parameterize server names
- 解决 Spring HttpMessageConverter 解析多余属性出错问题:DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
- IDEA启动项目报错:Caused by: java.io.FileNotFoundException: class path resource [.properties] cannot be opened because it does not exist