Search code examples
javapropertiesinputstreamoutputstreamrestart

Read from property file after restarting program


I'm trying to save my config data in the config.properties file. I'm saving my properties like this:

public static void setProperty(Parameter property) {

    // set the property's value
    prop.setProperty(property.getIndex(), property.getValue());

    // save properties to project root folder
    try {
        prop.store(output, null);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

and load them like this:

public static String getProperty(String componentName) {

    // get the property value
    return prop.getProperty(componentName);
}

and everything works fine, but when I restart my program, I don't have any properties anymore. I call following method in the beginning of my program for loading my property file:

static String FILE = "config.properties";
static InputStream input;
static OutputStream output;
static Properties prop = new Properties();

public static void loadExistingProperties() {
    try {
        input = new FileInputStream(FILE);
        output = new FileOutputStream(FILE);

        // load properties from file
        prop.load(input);
        System.out.println("amount of saved properties: " + prop.size());

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Can anyone tell me why I can't find my properties anymore after restarting the program? Is the way I'm trying to get my prop wrong maybe? I have no idea how to do it in another way.


Solution

  • First problem is that whenever you modify a property, you write the whole properties to the output output stream. This is not how it was intended to work.

    The Properties.store() method will store all the properties stored in the Properties object. So you should open your file right before calling the store() method and close right after it.

    It looks to me that you never close output which might result in data written to it still existing only in in-memory cache and never written to the underlying file.

    Simply persist properties like this:

    try (OutputStream out = new FileOutputStream("config.properties")) {
        prop.store(out, null);
    }
    

    And load them simply like this:

    try (InputStream in = new FileInputStream("config.properties")) {
        prop.load(in);
    }
    

    The try-with-resources blocks will properly close the streams.

    Also you should not persist properties every time you modify one. Common thing is to only save properties/settings when you close the program or when the user asks you to do it (like a "Save settings now" menu).