Properties类的详细使用
Properties类继承了Hashtable类,以Map的形式进行放置值,以key=value的键值对的形式进行存储值,key值不能重复。
主要的方法:
Properties( ):构造方法
setProperty(String , String) :设置值
load(InputStream):加载文件
store(OutputStream, String):保存文件
loadFromXML(InputStream):加载xml文件
storeToXML(OutputStream,String):保存到xml文件
getProperty(String):获取属性值
stringPropertyNames():输出key值
list(PrintWriter):输出打印
实例代码:打印JVM参数
@Test
public void printTest(){
Properties prop = System.getProperties();
Properties.list(System.out);
}
实例代码:打印properties文件中的值
public void printTest(){ try{
Properties prop = new Properties();
InputStream is = BufferedInputStream (new FileInputStream(new File("D:\jdbc.properties")));
prop.load(is);
prop.list(System.out);
} catch(IOException e){
e.printStackTrace()
}
}
实例代码:
public void printTest(){
try{
Properties prop = new Properties();
InputStream is = this.class.getClass().getResourceAsStream("/jdbc.properties");
prop.load(is);
Enumeration<String> name =(Enumeration<String>) prop.propertyNames();
while(name.hasMoreElements){
String key = name.nextElement();
String value = prop.getProperty (key);
System.out.println(value);
}
}catch (Exception e){
e.printStackTrace();
}
}
实例代码:
public void printTest(){ try{
Properties prop = new Properties();
InputStream is =this.class.getClassLoader().getResourceAsStream("/jdbc.properties");
prop.load(is);
Set<String> name = prop.stringPropertyNames();
Iterator<String> it = name.iterator();
while(iterator.hasNext()){
String key = iterator.next();
String value = prop.getProperty(key);
System.out.println(value);
}
}catch(Exception e){
e.printStackTrace();
}
}
实例代码:
public void writeTest(){ try {
Properties prop = new Properties();
prop.setProperty("name","测试")
OutputStream os = new FileOutputStream (new File ("D://jdbc.properties"));
OutputStreamWriter osw= new OutputStreamWriter(os,"utf-8");
prop.store(osw,"存储数据");
osw.fluse();
osw.close();
os.fluse();
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
实例代码:
public void XMLTest(){ try{
Properties prop = new Properties();
InputStream is = new FileInputStream(new File("d:\jdbc.xml"));
prop.loadFromXML(is);
prop.setProperty("name","测试")
OutputStream os = new FileOutputStream(new File("d:\test.xml"));
prop.storeToXML(os,"保存为XML","utf-8");
}catch(Exception e){
e.printStackTrace();
}
}
以上是 Properties类的详细使用 的全部内容, 来源链接: utcz.com/z/513612.html