Saves the property identified by key with the given value to the defined property File. - Java java.util

Java examples for java.util:Properties File

Description

Saves the property identified by key with the given value to the defined property File.

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Main {
    /**/*from ww w .j  ava  2 s .co m*/
     * Saves the property identified by key with the given value to the defined
     * propertyFile.
     * @param propertyFile
     * @param key
     * @param value 
     */
    public static void saveProperty(String propertyFile, String key,
            String value) {
        try {
            FileOutputStream out;
            File file = new File(propertyFile);

            //Creates directory if needed
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            //Creates property file if needed
            if (!file.exists()) {
                file.createNewFile();
            }

            Properties prop = new Properties();
            FileInputStream in = new FileInputStream(file.getAbsolutePath());
            prop.load(in);
            in.close();

            out = new FileOutputStream(file.getAbsolutePath());
            prop.setProperty(key, value.toString());
            prop.store(out, "UserData");
            out.close();

            System.out.println("Saved " + key + ":" + value);

        } catch (IOException e) {
            System.err.println(e);
        }
    }
}

Related Tutorials