我目前正在加载这样的属性文件:
private Properties loadProperties(String filename) throws IOException{
InputStream in = ClassLoader.getSystemResourceAsStream(filename);
if (in == null) {
throw new FileNotFoundException(filename + " file not found");
}
Properties props = new Properties();
props.load(in);
in.close();
return props;
}
但是,目前我的文件位于 scr\user.properties 路径。
但是当我想写入属性文件时:
properties.setProperty(username, decryptMD5(password));
try {
properties.store(new FileOutputStream("user.properties"), null);
System.out.println("Wrote to propteries file!" + username + " " + password);
这段代码在我的项目的根文件夹级别为我生成了一个新文件。
但是我想要一个文件来写/读。
那么该怎么做呢?
PS.: 当我想指定路径时,我得到“不允许修改文件...”
最佳答案
创建新文件的原因是因为您在编写时试图创建一个新文件。您应该首先获取要作为 File 对象写入的 user.properties 的句柄,然后尝试写入它。
代码看起来类似于
properties.setProperty(username, decryptMD5(password));
try{
//get the filename from url class
URL url = ClassLoader.getSystemResource("user.properties");
String fileName = url.getFile();
//write to the file
props.store(new FileWriter(fileName),null);
properties.store();
}catch(Exception e){
e.printStacktrace();
}
关于java - 如何从根目录加载属性文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322828/