如何把properties中的文件key和value全部读出来?

2024-11-28 16:53:21
推荐回答(3个)
回答1:

这是根据key读出value值的(key必须先知道):
Properties props = new Properties();
try {
props.load(ConnectionUtils.class.getClassLoader()
.getResourceAsStream("properties文件"));
} catch (IOException e) {
e.printStackTrace();
}
if (props != null) {
url = props.getProperty("url");
driver = props.getProperty("driver");
username = props.getProperty("username");
password = props.getProperty("password");
}
另外不知道key的话这样写:
new BufferedReader(new FileInputStream("properties文件")).readLine()一行一行读取,再处理下是Ok了

回答2:

Properties prop = new Properties();
FileInputStream fis = new FileInputStream("c:/log4j.properties");
prop.load(fis);
prop.list(System.out);
Object[] objs = prop.keySet().toArray();
for(int i=0;i System.out.println("key:"+objs[i]+",value:"+prop.get(objs[i]));
}

回答3:

public class Config {
//Properties继承于HashMap key:value都是String类型
private Properties table=new Properties();
public Config(String file){
try{
table.load(new FileInputStream(file));
}catch (IOException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
public int getInt(String key){
return Integer.parseInt(table.getProperty(key));
}
public String getString(String key){
return table.getProperty(key);
}
public double getDouble(String key){
return Double.parseDouble(table.getProperty(key));
}
}