Java的System类,Runtime类

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");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值