繁体   English   中英

设置Java系统属性,此代码为什么不起作用?

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

以下代码似乎不起作用,但我确定它曾经有用。

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

在构造新的Properties对象的过程中,不会添加旧的属性,因此在调用System.setProperties时,它具有擦除所有系统属性的效果。

奇怪的是,Oracle网站上有一个与此类似的代码示例。

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

有人可以解释为什么该代码不起作用吗? 而该代码应该代替什么呢?

我正在使用Java 1.7_75 64-0位。

谢谢Rich

看看Java文档 构造者

public Properties(Properties defaults)

如上所述

用指定的默认值创建一个空的属性列表。

创建一个新的Properties实例,但不使用输入参数中的属性对其进行初始化,它仅为此新实例设置默认值。

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();
            }
        }

    }
  }
}

就我而言,这是创建和保存属性的唯一方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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