Search code examples
javafilefilenotfoundexceptionoutputstreamproperties-file

How to load a properties file from classpath in Java


I'm trying to create a config file to save the username and ip data for a client inside the classpath, as in a resources folder in the project. I'm able to retrieve the properties like this:

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;

}

But I also want to be able to set those values which I can get from the file, so to attempt to do that, I use this method:

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();

    }

}

However, running that method gives me the following error:

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)

Now, I have confirmed that the file client-config.properties does exist, as I am able to read data from it, but it seems I'm unable to create an output stream for it. Why is that? Thank you in advance.

The problem I have is that I cannot open an output stream from the file in my classpath.


Solution

  • That property is inside your .jar-file. So your question should rather be "how to modify contents of the .jar file currently executing" which is not a good idea.

    The main question here would be:

    Do you need those values persisted?

    If the values you set should stay active only while program run that's fine - just .setProperty(key, value); and all's fine.

    If on the other hand you want those values to be persisted for the next start of the application, you'd might want to consider Preferences instead.