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

标签 java windows eclipse file properties

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

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/

相关文章:

java - XSRFTokenUtility 中的 NPE - Google 移动后端启动器

java - 我应该如何重写 equals 和 hashcode 方法以避免在 HashSet 中添加相等的对象?

Java Bucket排序另一个数组中的元素

c++ - WINAPI 枚举WindowsProc : Non-Standard Syntax; use & to create a point to a member

linux - 使用 Ant 复制到受限文件夹(在 Ubuntu 中使用 Eclipse)

java - 无法在 Eclipse Kepler 中使用 JD-Eclipse 反编译类

windows - 无法在 Windows 上构建 RuSTLess

windows - 站点到站点 VPN 与点到站点 VPN

linux - 使用 Eclipse 外部工具配置复制所有相同类型的文件

android - 视频动态壁纸安卓