Java 如何从根目录加载属性文件?
我当前正在加载一个属性文件,如下所示:Java 如何从根目录加载属性文件?,java,windows,eclipse,file,properties,Java,Windows,Eclipse,File,Properties,我当前正在加载一个属性文件,如下所示: private Properties loadProperties(String filename) throws IOException{ InputStream in = ClassLoader.getSystemResourceAsStream(filename); if (in == null) { throw new FileNotFoundException(filename + " fi
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);
这段代码在项目的根文件夹级别为我生成一个新文件
但是我想有一个文件要写\读
因此,如何做到这一点
注:当我想指定路径时,我会得到“不允许修改文件…”创建新文件的原因,因为您在写入时试图创建新文件。您应该首先获得要作为文件对象写入的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();
}
可能尝试更改权限?谢谢您的评论!但是你所描述的我已经在做了;(并且它不起作用……在您的情况下,新的FileOutputStream会创建一个新文件。在提供的解决方案中,您首先从系统资源获取文件名,然后使用文件编写器将其写入同一个文件。您为读写生成的文件对象应该与来自系统资源的文件对象相同。如果不起作用,请告诉我。