简体   繁体   中英

Setting Java system properties, why doesn't this code work?

The following code doesn't appear to work, and yet I'm sure it used to.

public static void main(String args[])
{
    Properties currentProperties = System.getProperties();
    Properties p = new Properties(currentProperties);
    System.setProperties(p);
}

During the construction of the new Properties object the old properties are not added, so when System.setProperties is called it has the effect of wiping all of the system properties.

What's also odd is there is an example of code similar to this on the Oracle website.

https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Could someone please explain why this code doesn't work? And what one should do in place of this code?

I am using Java 1.7_75 64-0-bit.

Thanks Rich

Take a look at Java docs . The constuctor

public Properties(Properties defaults)

as mentioned

Creates an empty property list with the specified defaults.

creates a new Properties instance, but doesn't initialize it with properties from the input parameter, it only sets default values for this new instance.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

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

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

    try {

        output = new FileOutputStream("config.properties");

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

        // save properties to project root folder
        prop.store(output, null);

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

    }
  }
}

As far as I am concerned this is the only way to create and save properties.

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