首页 > 解决方案 > Java Web 项目,属性文件未正确更新并错过循环中的某些位置

问题描述

我有一个循环运行n多次。在循环执行期间,updateConfigFile每次都会调用一个函数来更新config.properties文件。

这是使用的函数,如下所示:

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

问题是在循环期间,有时它会更新,有时不会。它可以在任何位置随机不更新。例如:

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

数据样本config.properties

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

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

当我根据属性运行这个循环时,值会改变。

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

谁可以帮我这个事。谢谢你。

标签: javajakarta-ee

解决方案


推荐阅读