繁体   English   中英

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

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

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

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

暂无
暂无

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

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