public class ReadSystemProperties {
public static void main(String[] args) {
// 通过获得系统属性构造属性类 prop
Properties prop = new Properties(System.getProperties());
// 在标准输出中输出系统属性的内容
prop.list(System.out);
//测试一下user.dir的内容
System.out.println(System.getProperty("user.dir"));
}
}
从输出中可以看到很多内容,比如源文件的编码(file.encoding),文件分隔符(file.separator)等等。
其实这个获取的是JVM系统环境属性 ,通过这个属性可以获得一些关于当前操作系统的一些基本信息。
System中有一个方法是getenv(),返回一个Map,可以显示所有的操作系统的环境变量,代码如下:
for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
如果要读取properties文件,那么一般的写法是怎么样的呢?
Properties prop = new Properties();
InputStream in = TestFile.class.getClassLoader().getResourceAsStream(
"map2.properties");
prop.load(in);
注意map2.properties文件要在classpath中,要不会出现文件找不到异常(filenotfoundexception),如果要遍历文件的键值对,那么该怎么做呢?
Set<Object> keyValue = prop.keySet();
for (Object o : keyValue) {
String key = (String) o;
System.out.println(key);
System.out.println(prop.getProperty(key));
}
还可以通过ResourceBundle读取properties文件,例如properties文件是这样的:
map.properties文件
JCP=HAPPY
Spec=Special
HAPPY=JCP
Welcome=HELLOWORLD
Spec=Special
HAPPY=JCP
Welcome=HELLOWORLD
ResourceBundle resource = ResourceBundle.getBundle("map");
System.out.println(resource.getString("JCP"));
注意代码中的文件名不需要写后缀,那么这段代码的输出为HAPPY。