【问题标题】:How to load a properties file from the root directory?如何从根目录加载属性文件?
【发布时间】:2012-11-10 14:20:48
【问题描述】:

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

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.:当我想指定路径时,我得到“不允许修改文件...”

【问题讨论】:

  • 也许尝试更改权限?

标签: java windows eclipse file properties


【解决方案1】:

创建新文件的原因是您在编写时尝试创建新文件。您应该首先获取要作为 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();
}

【讨论】:

  • 感谢您的评论!但是你所描述的我已经在做......;(它不起作用......
  • 在您的情况下,新的 FileOutputStream 创建一个新文件。在提出的解决方案中,您首先从系统资源中获取文件名,然后使用文件写入器将其写入同一个文件。您为读取和写入生成的文件对象应该与来自系统资源的文件对象相同。如果它不起作用,请告诉我。
猜你喜欢
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
  • 2013-12-19
  • 2011-09-26
  • 1970-01-01
  • 2017-06-28
  • 2017-07-25
相关资源
最近更新 更多