简体   繁体   中英

I need to overwrite the value in property file

My property file contains 3 properties I need to overwrite the value for thirdOne. How do I load the property file from class path in my java code and overwrite it..

my property file Location packagName->resource->folderName->.propertyFile

property File : I need to overwrite the value for "epochFromTime" :

FILE_PATH=C:\\Users\\pda\\Desktop\\JsonOutput\\DataExtract
epochFilename=C:\\Users\\pda\\Desktop\\JsonOutput\\epochTime.txt
epochFromTime=1545329531862

Java Code:

try {
            Properties config = new Properties();
                config.load(ClassLoader.getSystemResourceAsStream(PROPERTIES_PATH));
                String epochFromTimeChanged= Long.toString(epoch_to2);
                config.setProperty("epochFromTime",epochFromTimeChanged);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

This is pretty easy. First do read a property file to Properties . Then update it and save it afterwards. Do not forget to close resources.

public static void updateProperties(File file, Consumer<Properties> consumer) throws IOException {
    Properties properties = new Properties();

    try (Reader reader = new BufferedReader(new FileReader(file))) {
        properties.load(reader);
    }

    consumer.accept(properties);

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
        properties.store(writer, "comment");
    }

}

Client code could look like this:

updateProperties(
        new File("application.properties"),
        properties -> {
            properties.setProperty("two", "two_two_two");
            properties.setProperty("three", "three_three");
        });

application.properties

before update

two=two_two
one=one_one

after update

#comment
#Fri Jan 04 18:59:12 MSK 2019
two=two_two_two
one=one_one
three=three_three

Use Properties.store() to write the changed value back to the file:

String PROPERTIES_PATH = "...";
try {
    File f = new File(PROPERTIES_PATH);
    FileInputStream in = new FileInputStream(f);
    Properties config = new Properties();
    config.load(in);

    String epochFromTimeChanged= Long.toString(epoch_to2);
    config.setProperty("epochFromTime",epochFromTimeChanged);

    // get or create the file
    File f = new File(PROPERTIES_PATH);
    OutputStream out = new FileOutputStream(f);
    config.store(out, "My properties file comment");

} catch (FileNotFoundException e1) {
    log.info("{} does not exist", PROPERTIES_PATH);
} catch (IOException e) {
    log.error("Cannot access {}", PROPERTIES_PATH, e);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM