简体   繁体   English

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

[英]How to load a properties file from the root directory?

I am currently loading a properties file like this:我目前正在加载这样的属性文件:

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;
    }

However, at the moment my file lays at the scr\\user.properties path.但是,目前我的文件位于 scr\\user.properties 路径。

But when I want to write to a properties file:但是当我想写入属性文件时:

properties.setProperty(username, decryptMD5(password));
        try {
            properties.store(new FileOutputStream("user.properties"), null);
            System.out.println("Wrote to propteries file!" + username + " " + password);

That piece of code generates me a new file at the root folder level of my project.这段代码在我的项目的根文件夹级别为我生成了一个新文件。

BUT I want to have one file to write\\read.但我想要一个文件来写\\读。

Therefore how to do that?因此如何做到这一点?

PS.: When I want to specify the path I get "Not allowed to modify the file..." PS.:当我想指定路径时,我得到“不允许修改文件......”

The reason a new file is created because you are trying to create a new file when you are writing.创建新文件的原因是您在编写时尝试创建新文件。 You should first get handle to the user.properties that you want to write to as File object and then try to write to it.您应该首先获取要作为 File 对象写入的 user.properties 的句柄,然后尝试写入它。

The code would look something along the lines of代码看起来像

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM