如何从 Java 中的类路径加载属性文件

How to load a properties file from classpath in Java

我正在尝试创建一个配置文件以将客户端的用户名和 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.mouseClicked(ClientWindow.java:142)

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

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

属性 在您的 .jar 文件中。所以你的问题应该是 "how to modify contents of the .jar file currently executing" 这不是一个好主意。

这里的主要问题是:

您需要保留这些值吗?

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

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