properties 配置文件找不到路径
这种方法,百度上说,是能让
props.store(out, null);这个起作用
的,但是路径不行,找不对。。
求大家指教下。。。
有点点无奈,崩溃了。。。
居然被这种问题,拖住。。。
[解决办法]
把path打出来看看不就知道了
映象中应该是 realpath或者absolutPath
[解决办法]
你看看你的tomcat安装路径是不是有空格,这样获取的路径会自动把空格转义的,所以你无法获取正确路径。
[解决办法]
你把两种方法的path 打印出来看区别。
[解决办法]
改了一点,我这好使。这里改的是classpath下的config.properties,而不是src下的
public class Utils {
private static Properties props = null;
private static final String PATH = "/config.properties";
/**
* 得到config.properties配置文件中的所有配置属性
*
* <A href="http://home.51cto.com/index.php?s=/space/34010"
* target=_blank>@return</A> Properties对象
*/
public static Properties getConfig() {
if (null == props) {
props = new Properties();
// InputStream in = Utils.class.getResourceAsStream(PATH);
InputStream in;
try {
in = Utils.class.getResourceAsStream(PATH);
props.load(in);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return props;
}
/**
* 获得config.properties配置文件的属性值
* */
public static String getValue(String name) {
if (null == props)
getConfig();
return props.getProperty(name);
}
/**
* 设置config.properties配置文件的属性
* */
public static void setConfig(String name, String value) {
if (props == null)
getConfig();
props.setProperty(name, value);
// saveConfig();
}
/**
* 保存数据
*/
public static void saveConfig() {
try {
FileOutputStream out = new FileOutputStream(Utils.class.getResource("/config.properties").getPath());
props.store(out, null);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(getConfig().getProperty("aaa"));
setConfig("aaaa", "cccc");
saveConfig();
}
}
package com.spring.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class PropertiesUtil {
private static final String PROPERTIES_DEFAULT_PATH = "/config.properties";
public static String getProp(String key){
String result = "";
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream(PROPERTIES_DEFAULT_PATH);
try {
prop.load(in);
if(prop.containsKey(key)){
result = (prop.get(key)+"").trim();
}else{
result = "";
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static String getProp(String key,String path){
String result = "";
Properties prop = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream(path);
try {
prop.load(in);
if(prop.containsKey(key)){
result = (prop.get(key)+"").trim();
}else{
result = "";
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
*<p>功能描述:</p>
* @param args
* @return void
* @throws
**/
public static void main(String[] args) {
System.out.println(PropertiesUtil.getProp("jdbc.url"));
}
}