Properties类
Properties是hashtable的子类,具备map集合的特点,而且存储的键值对都是字符串
是集合中和IO技术相结合的集合容器
用处:用于键值对形式的配置文件
构造函数
Properties prop=new Properties();
1.集合方法:
设置:
prop.setProperty("lisi", "39");
获取:
Set<String> names=prop.stringPropertyNames();
for(String s:names)
{
System.out.println(s+":"+prop.getProperty(s));
}
2.与IO流相结合的特有方法
读取:
prop.load(InputStream inStream)
从读取流中读取属性列表(键和元素对),加载进集合 。
写入:
prop.store(OutputStream,"String");
当前集合内容写入字符流 ,"String"--注释
打印:
prop.list(PrintStream out)
将此属性列表(集合)打印到指定的输出流中。 如System.out
使用配置文件记录软件使用次数
package 黑马IO流_Properties类;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/*
使用配置文件:
*/
public 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);
String value=prop.getProperty("time");
int count=0;
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();
}
}
获取系统配置信息
package 黑马IO流_Properties类;
/*
System:类中的方法和属性都是静态的
out:标准输出,默认是控制台
in:标准输入,默认是键盘
描述系统一些信息。
获取系统属性信息:Properties getProperties();
在系统中自定义一些特有信息:System.setProperty("myKey","myvalue");
获取指定属性信息:System.getProperty("os.name");
在jvm启动时,动态加载一些属性信息-D<name>=<value>;
*/
import java.util.*;
public class SystemDemo {
public static void main(String[] args) {
Properties prop=System.getProperties();
//因为Properties是HashTable的子类,也就是Map集合的一个子类对象
//那么可以通过map的方法取出该集合中的元素
//该集合中存储的都是字符串,没有泛型定义
//如何在系统中自定义一些特有信息:
System.setProperty("myKey","myvalue");
//获取指定属性信息:
String value=System.getProperty("os.name");
System.out.println("os.name="+value);
//在jvm启动时,动态加载一些属性信息-D<name>=<value>;
// 获取所有属性信息
// for(Object obj:prop.keySet()) {
// String value=(String)prop.get(obj);
// System.out.println(obj+"::"+value);
// }
}
}
获取系统信息存储到文件中
package 黑马IO流_Properties类;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
//获取系统信息存储到文件中
public class SystemInfo {
public static void main(String[] args)throws IOException
{
Properties prop=System.getProperties();
prop.list(new PrintStream("sysinfo.txt"));
}
}
运行结果