系统相关

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是不同对象,所以返回false
		String 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值