|
如何一次性将整个properties文件里面的配置内容读取出来,现在我想到的就是直接读取文件的方式,但是这种方式读取的效率不行吧,求大神解答。。。(分数不多,谅解) |
|
![]() 5分 |
package com.mkyong.properties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class App {
public static void main(String[] args) {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("database"));
System.out.println(prop.getProperty("dbuser"));
System.out.println(prop.getProperty("dbpassword"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
![]() 5分 |
Properties本身就是个Hashtable,可以像HashMap那样遍历出来。
|
![]() |
@lds1ove 对于您的代码来说需要知道整个properties文件中的key值,现在就是不想把所有的key都列出来。。。@rmn190 您好,能说的清晰一些吗?
|
![]() |
一个properties文件才多大点,全部读出来放内存里多好。 |
![]() 5分 |
想这样,就不要弄成properties文件啊,直接xml,读取整个xml,转成map或json,想怎么玩怎么玩
|
![]() |
api本身提供了keys和keyset方法。
|
![]() |
package com.ssh.util;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class ProperUtil {
private static final String fileName = "/com/ssh/config/properties/system.properties";
private static Properties proper = new Properties();
static{
try {
proper.load(ProperUtil.class.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getStringValue(String key,String defultValue){
String value = proper.getProperty(key);
if(HelpUtil.checkEmpty(value)){
return defultValue;
}
return value;
}
public static boolean getBooleanValue(String key,boolean defultValue){
String value = proper.getProperty(key);
if(HelpUtil.checkEmpty(value)){
return defultValue;
}
return Boolean.parseBoolean(value);
}
public static Integer getIntegerValue(String key,Integer defultValue){
String value = proper.getProperty(key);
if(HelpUtil.checkEmpty(value)){
return defultValue;
}
return Integer.parseInt(value);
}
/**
* 读取所有的配置文件信息
* */
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;
}
}
这样可以一次性取到整个properties文件的配置 |
![]() 5分 |
楼上已经给出代码了,如果楼主觉得想要更强大功能可以采用apache-commons-configuration;支持getInt等类型的获取
进入http://commons.apache.org/下载 |

