Properties类读写.properties文件和.xml文件
-
Properties类:该类继承自HashMap类,同时实现了Map的方法,存取形式利用键值对的形式,与Map的区别在于,键和值只能是字符串的形式。
-
读properties文件:load()将文件输入流加载到Properties对象。
public void readProperties(){
Properties prop=new Properties();
try {
FileInputStream fis=new FileInputStream("Test.properties");
prop.load(fis);
fis.close();
Iterator it=prop.stringPropertyNames().iterator();
while(it.hasNext()){
String key=(String)it.next(); System.out.println(key+":"+prop.getProperty(key));
}
prop.list(System.out);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
3.写properties文件:store()将文件输出流存储到properties对象。public void writeProperties(){
Properties prop=new Properties();
try {
FileOutputStream fos=new FileOutputStream("Test.properties",true);
prop.setProperty("ip", "192.168.2.1");
prop.setProperty("port", "1001");
prop.store(fos, null);
fos.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
4.读XML文件:loadFromXML()将XML输入流加载到properties对象。public void readXml(){
Properties prop=new Properties();
try {
FileInputStream fis=new FileInputStream("Test.xml");
prop.loadFromXML(fis);
fis.close();
prop.list(System.out);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
5.写XML文件:storeToXML()将文件输出流写入到Properties对象。public void writeXml(){
Properties prop=new Properties();
try {
FileOutputStream fos=new FileOutputStream("Test.xml",true);
prop.setProperty("ip", "192.168.2.1");
prop.setProperty("port", "1001");
prop.storeToXML(fos, "start");
fos.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
6、getProperty()/ setProperty()取键值,设置键值