简体   繁体   中英

Unable to read properties file after creating it

I am creating a properties file and putting into my classpath folder Resources. When I tried to read this file , i am not getting the expected result. i am getting the result of the previous values printed instead of the property values set now. My class file is as follows :

public class App {
  public static void main(String[] args) {

    Properties prop = new Properties();
    PrintWriter output = null;

    try {

        output = new PrintWriter("Resources/config.properties");

        // set the properties value
        prop.setProperty("database", "localhost");
        prop.setProperty("dbuser", "mkyong");
        prop.setProperty("dbpassword", "password");

        // save properties to project root folder
        prop.store(output, null);
        if(output!=null) {
            System.out.println("Output");

            output.close();

        }

    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (output != null) {

                output.close();

        }

    }

    Properties prop1 = new Properties();
    BufferedInputStream input = null;

    try {

        String filename = "config.properties";
        input =  (BufferedInputStream) AppCPLoad.class.getClassLoader().getResourceAsStream(filename);
        if(input==null){
                System.out.println("Sorry, unable to find " + filename);
            return;
        }

        //load a properties file from class path, inside static method

        prop1.load(input);

            //get the property value and print it out
            System.out.println(prop1.getProperty("database"));
            System.out.println(prop1.getProperty("dbuser"));
            System.out.println(prop1.getProperty("dbpassword"));
            if(input!=null) {
                System.out.println("Input");
                input.close();
            }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally{
        if(input!=null){
            try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        }
    }
  }
}

Please help.

When you run the program, the properties file is loaded and the values are read. After you rewrite the properties file, that doesn't mean that the properties you have loaded already have be to rewritten. You need to reload the properties file and re-read the values . You are looking for an implementation like ReloadableResourceBundleMessageSource

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