1.一次性读取.properties文件的内容
Properties本身就是个Hashtable,可以像HashMap那样遍历出来。
1)配置文件config.properties与ProperUtil类、Test类放在同级,里面的内容如:
username=zhangsan
password=123
2)读取文件的方法类:
public class ProperUtil {
private static final String fileName = "config.properties";private static Properties proper = new Properties();
static{
try {
proper.load(ProperUtil.class.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<String, String> getAllProperties(){
Map<String, String> map = new HashMap<String, String>();
Enumeration en = proper.propertyNames();
String key = "";
String value = "";
while(en.hasMoreElements()){
key = (String)en.nextElement();
value = proper.getProperty(key);
map.put(key, value);
}
return map;
}
}
3)测试方法类:
public class Test {
public static void main(String[] args) {
Map<String,String> map=ProperUtil.getAllProperties();
System.out.println(map.size());
System.out.println(map.get("username"));
System.out.println(map.get("password"));
}
}
经过测试能够读出文件中的username与password
2..properties文件路径相关问题
图上的src/main/java,src/main/resources-dev,src/main/resources,src/test/java这几个文件下的一级目录都是放在web应用程序的根目录(‘/’Web应用程序的根目录的绝对路径)
解释:用下面的方式读取system.config.properties文件
String fileName = "config.properties";
Properties proper = new Properties();
proper.load(ProperUtil.class.getResourceAsStream(fileName));
应该写String fileName = "/system.config.properties";
当这个配置文件在com/下
应该写为String fileName = "/com/system.config.properties";