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

如何在Java中从类路径加载属性文件,java,file,filenotfoundexception,outputstream,properties-file,Java,File,Filenotfoundexception,Outputstream,Properties File,我正在尝试创建一个配置文件,以便在类路径中保存客户端的用户名和ip数据,就像在项目的资源文件夹中一样。我可以检索如下属性: public String getProperty(String property){ String result = null; try{ InputStream inputStream = this.getClass().getResourceAsStream(filename); Properties proper

我正在尝试创建一个配置文件,以便在类路径中保存客户端的用户名和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)
java.io.FileNotFoundException:file:/home/andrew/Documents/Programming/Executable JARs/SchoolClient.jar/client-config.properties(无此类文件或目录)
在java.io.FileOutputStream.open(本机方法)
位于java.io.FileOutputStream。(FileOutputStream.java:221)
位于java.io.FileOutputStream。(FileOutputStream.java:110)
位于com.andrewlalis.utils.DataSaver.setProperty(DataSaver.java:54)
位于com.andrewlalis.MainClient.getNewIp(MainClient.java:173)
在com.andrewlalis.ClientWindow$4.mouseClicked(ClientWindow.java:142)
现在,我已经确认文件
client config.properties
确实存在,因为我可以从中读取数据,但似乎无法为其创建输出流。为什么呢?先谢谢你


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

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

这里的主要问题是:

您需要保留这些值吗?

如果您设置的值应该仅在程序运行时保持活动状态,这很好-只需
.setProperty(键,值)一切都很好


如果另一方面你希望这些值在下一个应用程序的开始时被保留,你可能会想考虑。

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