Search code examples
javaproperties-fileread-write

Properties file reads old data when jar is executed from command line


I have created a java application that copies data from properties file (resources-> settings -> config.properties) and uses it. At one point the properties file values are updated and the code has to use the new values. The code works fine when executed from Netbeans. But when I execute ti from the dist folder after build, the old values get loaded everytime even when I change the the properties file. The properties file gets updated but the values used are still the old ones.

Code to write properties file

File f = new File(System.getProperty("user.dir") + "\\resources\\settings\\config.properties");

    try (OutputStream output = new FileOutputStream(f)) {

        Properties prop = new Properties();

        // set the properties value
        prop.setProperty("xml", xmlFileTextBox.getText());

        // save properties to project root folder.
        prop.store(output, null);

    } catch (IOException exception) {
        exception.printStackTrace();
    }

Code to read values in properties file

try {
        Properties prop = new Properties();
        String propFileName = "settings/config.properties";

        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName)) {
            if (inputStream != null) {
                prop.load(inputStream);
                xmlFileTextBox.setText(prop.getProperty("xml"));                                                       
            } 
            inputStream.close();
        }

    } catch (Exception e) {
        System.out.println("Exception: " + e);}

Solution

  • The file you are reading from is a file that is packaged with your application and not the file you are saving to.

    This code, getClass().getClassLoader().getResourceAsStream(propFileName)), gives you a resource from the classpath. You need to create the File in the same way as when you save the properties, then get the InputStream from that File.

    If you want to have the defaults in your original properties file you might need to check for null in the "save file" and if it don't have data then read from your default resourse file.