1.Propertis类:
Propertis:属性集合类(属性列表)是一个Map,但是没有泛型,键和值都是String
*
* 特有功能:
* public Object setProperty(String key,String value):添加键和值
* public Set<String> stringPropertyNames():获取所有 键的集合
* public String getProperty(String key):获取键对应的值
* public void store(Writer writer, String comments):将属性列表中的内容保存指定的文件中
* 参数2:给属性列表一个描述
*
* public void load(Reader reader):将文件中的内容加载属性列表中
public class PropertiesTest {
public static void main(String[] args) throws IOException {
myLoad() ;
//有一个属性列表
Properties prop = new Properties() ;
prop.setProperty("孙杰","30") ;
prop.setProperty("臧永青","25") ;
prop.setProperty("陈荣昌","28") ;
prop.setProperty("陈琛","28") ;
prop.setProperty("遆子林","25") ;
prop.setProperty("于水利","26") ;
//将属性列表中的内容保存指定文件中
Writer w = new FileWriter("name.txt") ;
prop.store(w,"name's list") ;
//释放资源
w.close() ;
}
//将文件中加载进来,将属性列表中内容可以遍历
private static void myLoad() throws IOException {
Reader r = new FileReader("Lucky.txt") ;
//创建空的列表
Properties prop = new Properties() ;
//System.out.println(prop);
prop.load(r);
//System.out.println(prop);
//获取所有的值
/* Collection<Object> values = prop.values();
for(Object obj :values){
System.out.println(obj);
}*/
Set<String> keySet = prop.stringPropertyNames();
for(String key :keySet){
String value = prop.getProperty(key);
System.out.println(key+"="+value) ;
}
}
}
----------------------加载src 目录 下的文件.properties--------------------------
private static void method() throws IOException {
//文件在哪个了中要读:
//1)获取当前了类的字节码文件对象
/*Class c = Test2.class ;
//2)获取类加载器
ClassLoader classLoader = c.getClassLoader();
//3)通过类加载获取当前src目录下面的配置文件所在的输入流对象
InputStream inputStream = classLoader.getResourceAsStream("name.properties");*/
InputStream inputStream =
Test2.class.getClassLoader().getResourceAsStream("name.properties");
//创建Properties
Properties prop = new Properties() ;
prop.load(inputStream);
System.out.println(prop) ;
}