How to write values in a properties file through java code

前端 未结 4 1912
庸人自扰
庸人自扰 2020-11-30 09:30

I have an issue.

I have a properties file. I want to store some values in that file and will implement in the code whenever it is required. Is there any way to do t

4条回答
  •  Happy的楠姐
    2020-11-30 10:09

    You can do it in following way:

    1. Set the properties first in the Properties object by using object.setProperty(String obj1, String obj2).

    2. Then write it to your File by passing a FileOutputStream to properties_object.store(FileOutputStream, String).

    Here is the example code :

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.File;
    
    class Main
    {
        static File file;
        static void saveProperties(Properties p) throws IOException
        {
            FileOutputStream fr = new FileOutputStream(file);
            p.store(fr, "Properties");
            fr.close();
            System.out.println("After saving properties: " + p);
        }
    
        static void loadProperties(Properties p)throws IOException
        {
            FileInputStream fi=new FileInputStream(file);
            p.load(fi);
            fi.close();
            System.out.println("After Loading properties: " + p);
        }
    
        public static void main(String... args)throws IOException
        {
            file = new File("property.dat");
            Properties table = new Properties();
            table.setProperty("Shivam","Bane");
            table.setProperty("CS","Maverick");
            System.out.println("Properties has been set in HashTable: " + table);
            // saving the properties in file
            saveProperties(table);
            // changing the property
            table.setProperty("Shivam", "Swagger");
            System.out.println("After the change in HashTable: " + table);
            // saving the properties in file
            saveProperties(table);
            // loading the saved properties
            loadProperties(table);
        }
    }
    

提交回复
热议问题