正在设置 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 位。
谢谢
富有
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();
}
}
}
}
}
据我所知,这是创建和保存属性的唯一方法。
看看Java docs。构造函数
public Properties(Properties defaults)
如前所述
Creates an empty property list with the specified defaults.
创建一个新的 Properties 实例,但不使用输入参数中的属性对其进行初始化,它只为这个新实例设置默认值。
以下代码似乎不起作用,但我确信它曾经起作用。
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 位。
谢谢 富有
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();
}
}
}
}
}
据我所知,这是创建和保存属性的唯一方法。
看看Java docs。构造函数
public Properties(Properties defaults)
如前所述
Creates an empty property list with the specified defaults.
创建一个新的 Properties 实例,但不使用输入参数中的属性对其进行初始化,它只为这个新实例设置默认值。