属性一般都是通过字符串数据实现的键值对(key=value,根据key找到对应的value)数据定义,在Java中可以使用Properties类进行操作
Properties类虽然是Hashtable的子类,但是其可以操作的数据类型只能是String
范例:属性操作
package com.lxh.eighteenchapter;
import java.util.Properties;
public class JavaCollectionDemo512 {
public static void main(String[] args) {
Properties prop=new Properties();//属性存储
prop.setProperty("及时雨", "宋江");//设置属性内容
prop.setProperty("行者", "武松");//设置属性内容
System.out.println(prop.getProperty("及时雨"));//根据key查找属性
System.out.println(prop.getProperty("花和尚"));//根据key查找属性
System.out.println(prop.getProperty("花和尚","鲁智深"));//根据key查找属性
}
}
执行结果
宋江
null
鲁智深
当查找属性不存在时,可以设置默认值
范例:将属性内容保存到文件中
package com.lxh.eighteenchapter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class JavaCollectionDemo512B {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop=new Properties();//属性存储
prop.setProperty("及时雨", "宋江");
prop.setProperty("黑旋风", "李逵");
prop.store(new FileOutputStream(new File("E:"+File.separator+"File"+File.separator+"ll.properties")), "哈哈");
}
}
执行结果
范例:通过Properties读取属性文件
package com.lxh.eighteenchapter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class JavaCollectionDemo513 {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties prop=new Properties();
prop.load(new FileInputStream(new File("E:"+File.separator+"File"+File.separator+"ll.properties")));
System.out.println(prop.getProperty("及时雨")); // 获取属性内容
}
}
执行结果
宋江