Java的System类,Runtime类

来源:互联网 发布:windows swift 编译器 编辑:程序博客网 时间:2024/05/22 03:41

System类代表当前Java程序的支行平台,程序不能创建System类的对象。

获得环境变量:

public class SystemTest{public static void main(String[] args) throws Exception{// 获取系统所有的环境变量Map<String,String> env = System.getenv();for (String name : env.keySet()){System.out.println(name + " ---> " + env.get(name));}// 获取指定环境变量的值System.out.println(System.getenv("JAVA_HOME"));// 获取所有的系统属性Properties props = System.getProperties();// 将所有系统属性保存到props.txt文件中props.store(new FileOutputStream("props2.txt"), "System Properties");// 输出特定的系统属性System.out.println(System.getProperty("os.name"));}}

System类还提供了一个identityHashCode(Object x)方法,该方法返回指定对象的精确hashCode值,也就是根据该对象的地址计算得到的hashCode值。当某个类的hashCode()方法被重写后,该类实例的hashCode()方法就不能唯一地标识该对象;但通过identityHashCode()方法返回的hashCode值,依然是根据该对象的地址计算得到的hashCode值。所以,如果两个对象的identityHashCode值相同,则两个对象绝对是同一个对象。

public class IdentityHashCodeTest{public static void main(String[] args){// 下面程序中s1和s2是两个不同对象String s1 = new String("Hello");String s2 = new String("Hello");// String重写了hashCode()方法——改为根据字符序列计算hashCode值,// 因为s1和s2的字符序列相同,所以它们的hashCode方法返回值相同System.out.println(s1.hashCode()+ "----" + s2.hashCode());// s1和s2是不同的字符串对象,所以它们的identityHashCode值不同System.out.println(System.identityHashCode(s1)+ "----" + System.identityHashCode(s2));String s3 = "Java";String s4 = "Java";// s3和s4是相同的字符串对象,所以它们的identityHashCode值相同System.out.println(System.identityHashCode(s3)+ "----" + System.identityHashCode(s4));}}

Runtime类代表Java程序的运行时环境,每个Java程序都有一个与之对应的Runtime实例,应用程序通过该对象与其运行时环境相连。应用程序不能自己创建自己的Runtime实例,但可以通过getRuntime()方法获取与之关联的Runtime对象。
通过Runtime类可以访问JVM的相关信息,如处理器数据,内存信息等。

public class RuntimeTest{public static void main(String[] args){// 获取Java程序关联的运行时对象Runtime rt = Runtime.getRuntime();System.out.println("处理器数量:"+ rt.availableProcessors());System.out.println("空闲内存数:"+ rt.freeMemory());System.out.println("总内存数:"+ rt.totalMemory());System.out.println("可用最大内存数:"+ rt.maxMemory());}}

Runtime类还有一个功能,它可以直接单独启动一个进程来运行操作系统的命令。

public class ExecTest{public static void main(String[] args)throws Exception{Runtime rt = Runtime.getRuntime();// 运行记事本程序rt.exec("notepad.exe");}}