日期:2014-05-20  浏览次数:20748 次

properties 配置文件找不到路径
 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 = new FileInputStream(Utils.class.getClass()
.getClassLoader().getResource(PATH).getPath());
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(new File(PATH));
props.store(out, null);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


自己写了个配置文件的工具类。。
用这个就能正确获得路径
in = Utils.class.getResourceAsStream(PATH);

而这种的话就不行
in = new FileInputStream(Utils.class.getClass().getClassLoader().getResource(PATH).getPath());

我本来是想这样的,可以修改配置文件的内容,但是百度了,
in = Utils.class.getResourceAsStream(PATH);
这种方法貌似是不能修改配置文件的。。。
只能通过其它方法,例如这种:
in = new FileInputStream(Utils.class.getClass().getClassLoader().getResource(PATH).getPath());
但是发觉无论我怎么改,都是找不对路径。。。
我的路径是放在src文件夹下 下面的:

现在主要的问题是:
props.store(out, null);
这个不起作用的,修改不了配置文件。。。

in = new FileInputStream(Utils.class.getClass().getClassLoader().getResource(PATH).getPath());