【问题标题】:Setting Java system properties, why doesn't this code work?设置Java系统属性,为什么这段代码不起作用?
【发布时间】:2015-10-02 12:49:41
【问题描述】:

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

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 位。

谢谢 丰富

【问题讨论】:

  • 什么不起作用?你的代码最终什么都不做。
  • 你也可以包含导入语句吗?
  • 如果要擦,不应该是Properties p = new Properties();吗?

标签: java properties system


【解决方案1】:

看看Java docs。构造函数

public Properties(Properties defaults)

如前所述

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

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

【讨论】:

    【解决方案2】:
    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();
                }
            }
    
        }
      }
    }
    

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

    【讨论】:

    • 这没有回答问题。
    • 你有什么建议改进=我正在尝试给他通常用于属性文件的代码,这样他可能会看到错误。我不确定他想要达到什么目标,所以这是我能做的最好的。
    • 您的代码很好,但是您正在从文件读取和写入,而 OP 正在使用系统属性。
    猜你喜欢
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多