【问题标题】:How to load a properties file from classpath in Java [duplicate]如何从Java中的类路径加载属性文件[重复]
【发布时间】:2016-03-10 08:43:33
【问题描述】:

我正在尝试创建一个配置文件,以将客户端的用户名和 ip 数据保存在类路径中,如项目中的资源文件夹中。我可以像这样检索属性:

public String getProperty(String property){

    String result = null;

    try{

        InputStream inputStream = this.getClass().getResourceAsStream(filename);
        Properties properties = new Properties();

        if (inputStream != null){

            properties.load(inputStream);
            System.out.println(this.getClass().getResource(filename).toString());

        }else {

            System.out.println("File not found or loaded: "+filename);

        }

        result = properties.getProperty(property, null);

        inputStream.close();

    }catch (Exception e){
        e.printStackTrace();            
    }

    return result;

}

但我也希望能够设置我可以从文件中获取的值,所以为了尝试这样做,我使用了以下方法:

public void setProperty(String property, String value){

    try{

        OutputStream out = new FileOutputStream(this.getClass().getResource(filename).getFile());
        Properties properties = new Properties();

        properties.setProperty(property, value);
        properties.store(out, "Optional comment");
        out.close();

    }catch (Exception e){

        System.out.println("Unable to load:"+filename);
        e.printStackTrace();

    }

}

但是,运行该方法会出现以下错误:

java.io.FileNotFoundException: file:/home/andrew/Documents/Programming/Executable-JARs/SchoolClient.jar!/client-config.properties (No such file or directory)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
at com.andrewlalis.utils.DataSaver.setProperty(DataSaver.java:54)
at com.andrewlalis.MainClient.getNewIp(MainClient.java:173)
at com.andrewlalis.ClientWindow$4.mouseClicked(ClientWindow.java:142)

现在,我已经确认文件client-config.properties 确实存在,因为我可以从中读取数据,但似乎我无法为其创建输出流。这是为什么?先感谢您。

我遇到的问题是我无法从类路径中的文件打开输出流。

【问题讨论】:

  • 这个问题比较含糊,因为我觉得答案不是简单的,“不,你不能在classpath中保存文件。”
  • 将输出文件写入其他位置,而不使用 ResourceAsStream 加载。试试绝对路径。

标签: java file filenotfoundexception outputstream properties-file


【解决方案1】:

该属性位于您的 .jar 文件中。因此,您的问题应该是“如何修改当前正在执行的 .jar 文件的内容”,这不是一个好主意。

这里的主要问题是:

您需要保留这些值吗?

如果您设置的值应该只在程序运行时保持活动状态,那很好 - 只需 .setProperty(key, value); 就可以了。

另一方面,如果您希望在下次启动应用程序时保留这些值,您可能需要考虑使用Preferences

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2016-08-09
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 2018-12-31
    • 1970-01-01
    相关资源
    最近更新 更多