Properties读取属性文件

import java.util.*;
import java.io.*;
class PropertiesDemo
{
public static void main(String[] args) throws Exception
{
String url = "prop.properties";
setAndGet(url);
}
public static void setAndGet(String url) throws Exception {
File file = new File(url);
if(!file.exists()){
file.createNewFile();
}
FileInputStream fis = new FileInputStream(file);

Properties prop = new Properties();
// 从输入流中读取属性列表(键和元素对)。一定要先加载
prop.load(fis);
//往配置文件里存值,单并不会保存到配置文件中
prop.setProperty("url","localhost:8888");
//保存到配置文件中
//a.输出流
FileOutputStream fos = new FileOutputStream(file);
prop.store(fos,"配置数据库连接信息");

//得到所有的键,返回此属性列表中的键集,其中该键及其对应值是字符串,
//如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。
Set<String> set = prop.stringPropertyNames();
//遍历所有的key
for(String s:set){
String key = s;
String value = prop.getProperty(key);
System.out.println(key+"="+value);
}
fos.close();
fis.close();
}
}

posted @ 2017-04-23 18:10  侠客夜莺  阅读(187)  评论(0)    收藏  举报