gpt4 book ai didi

java - 如何从根目录加载属性文件?

转载 作者:可可西里 更新时间:2023-11-01 11:58:00 26 4
gpt4 key购买 nike

我目前正在加载这样的属性文件:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com