0

I have a loop that runs for n times. During the loop execution a function updateConfigFile will be call each time to update config.properties file.

Here is the function used as below:

public void updateConfigFile(String propertyName,String propertyValue) {
    InputStream is = null;
    // Instead of FileOutputStream I have used FileWriter which will be same result.
    FileOutputStream fos = null;
    try {
        URL config = Aclass.class.getClassLoader().getResource("config.properties");
        File file = Paths.get(config.toURI()).toFile();
        String absolutePath = file.getAbsolutePath();
        if(config != null) {
            File f1 = new File(absolutePath);
            
            is = Aclass.class.getClassLoader().getResourceAsStream("config.properties");
            
            Properties prop = new Properties();
            prop.load(is);
            prop.setProperty(propertyName,propertyValue);
            fos = new FileOutputStream(f1);
            prop.store(fos, "modified");
            
            fos.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally{
        if(is!=null){try{is.close();} catch(Exception e){e.printStackTrace();}
        }
        if(fos!=null){try{fos.close();} catch(Exception e){e.printStackTrace();}
        }
    }
}

The problem is that during the loop, sometime it's update and sometime don't. It can be randomly not update at any position. For example:

Loop for 5 times.
Loop 0: Config file updated
Loop 1: Config file updated
Loop 2: Config file not updated
Loop 3: Config file updated
Loop 4: Config file updated

Loop for 7 times.
Loop 0: Config file updated
Loop 1: Config file updated
Loop 2: Config file updated
Loop 3: Config file updated
Loop 4: Config file not updated
Loop 5: Config file updated
Loop 6: Config file updated

Sample of config.properties data:

0_path="/home/abc/"
1_path="/opt/dev/"

0_file="abc.txt"
1_file="dev.txt"

When I run this loop based on the property the value will changed.

public void saveConfig(String name, String name_value){
    int n = 2;
    for(int a = 0; a < n; a++){
        updateConfigFile(i+"_"+name, name_value);
    }
}

Can any one help me on this. Thank you.

  • Can you also share the code which is calling `updateConfigFile` ? I think it might help to understand how you define 'Config file updated' state. – rxn1d Jun 22 '20 at 06:51
  • Already edited to add the calling method. – Ershad Ahamed Jun 23 '20 at 08:18
  • I found an answer, Sorry for the long delay. Loading from .properties file loads on memory that why the values doesn't change. But it does change the data on preperties file. – Ershad Ahamed Sep 17 '20 at 10:56

0 Answers0