系统相关

来源:互联网 发布:gamemaker 源码 编辑:程序博客网 时间:2024/05/21 04:39

1.System类代表java程序的运行平台,程序不能创建System类的对象,System类提供了一些类变量和类方法,允许直接通过System类来调用这些类变量和类方法。

import java.util.*;import java.io.*;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.store(new FileOutputStream("props.txt"),"System Properties");  //将所有的系统属性保存在props.txt文件中System.out.println(System.getProperty("os.name"));   //输出特定的系统属性}}


2.System类还有两个获取系统当前时间的方法:currentTimeMillis()和nanoTime(),它们都返回一个long型整数。实际上它们都返回当前时间与UTC 1970年1月1日午夜的时间差,前者以毫秒作为单位,后者以纳秒作为单位。

除此之位,System类的in,out和err分别代表系统的标准输入(通常是键盘)、标准输出(通常是显示器)和错误输出流,并提供了setIn(),setOut()和setErr()方法来改变系统的标准输入、标准输出和标准错误输出流。


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

public class IdentityHashCodeTest{public static void main(String[] args){String s1 = new String("Hello");String s2 = new String("Hello");System.out.println(s1.hashCode()==s2.hashCode()); //因为String类重写过hashCode()方法:根据字符序列计算hashCode值System.out.println(System.identityHashCode(s1)==System.identityHashCode(s2));//s1和s2是不同对象,所以返回falseString s3 = "hey";String s4 = "hey";System.out.println(System.identityHashCode(s3)==System.identityHashCode(s4));//因为字符串保留在常量池中,所以s3和s4指向同一个地址}}


4.Runtime类代表Java程序运行时的环境,每个Java程序都有一个与之对应的Runtime实例,应用程序通过该对象与其运行时环境相连。应用程序不能创建自己的Runtime实例,但可以通过getRunntime()方法获取与之关联的Runtime对象。

与System类似的是,Runtime类也提供了gc()方法和runFinalization()方法来通知系统进行垃圾回收、清理系统资源,并提供了load(String filename)和loadLibrary(String libname)方法来加载文件和动态链接库。

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

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

public class runtimetest{public static void main(String[] args) throws Exception{Runtime rt = Runtime.getRuntime();    //获取Java程序关联的运行时对象rt.exec("notepad.exe");  //通过exec()方法来运行操作系统命令}}


0 0
原创粉丝点击