一:简介
• Properties
–继承于Hashtable
–可以将K-V对保存在文件中
–适用于数据量少的配置文件
–继承自Hashtable的方法:clear, contains/containsValue, containsKey,
get, put,remove, size
–从文件加载的load方法, 写入到文件中的store方法
–获取属性 getProperty ,设置属性setProperty
–查看PropertiesTest了解其用法
二:Properties文件的创建
选中properties文件要创建的包
file->new->Resource Bundle->输入文件名称
如图Map包下成功创建了名为test的Properties文件
三:Properties文件相关操作,见PropertiesTest.java
public class PropertiesTest {
public static String GetValueByKey(String fileName,String key){//获取单个属性值
Properties pps=new Properties();
String value;
try {
InputStream in =new BufferedInputStream(new FileInputStream(fileName));
pps.load(in);//只取一个也要加载所有K-V对
value=pps.getProperty(key);
return value;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void GetAllProperties(String fileName) throws IOException {//获取所有属性值
Properties pps=new Properties();
InputStream in =new BufferedInputStream(new FileInputStream(fileName));
pps.load(in);
Enumeration enu=pps.propertyNames();//通过枚举类来承载所有属性名
while (enu.hasMoreElements()){
String key=(String)enu.nextElement();//获取单个属性
String value=pps.getProperty(key);//通过Key值获取属性内容
System.out.println("{ "+key+":"+value+"}");
}
}
//写入Properties信息
public static void writeProperties(String fileName,String key,String value) throws IOException {
File file=new File(fileName);
if(!file.exists())
{
file.createNewFile();
}
Properties pps=new Properties();
InputStream in=new FileInputStream(fileName);
pps.load(in);//加载所有原来的K-V对
OutputStream out=new FileOutputStream(fileName);
pps.setProperty(key,value);//写入一个K-V对
pps.store(out,"update "+key+":"+value);//将所有K-V对写回到文件中
out.close();
}
public static void main(String[] args) throws IOException {
String filePath="src\\Map\\test.properties";
writeProperties(filePath,"cxy","good");
writeProperties(filePath,"test","success");
GetAllProperties(filePath);
System.out.println(GetValueByKey(filePath,"cxy"));
}
}
程序生成的Properties文件截图: