System 类 和 Runtime 类的常用用法介绍

2022-10-20,,,,

system类的常用用法
1,主要获取系统的环境变量信息
复制代码 代码如下:
public static void sysprop()throws exception{
  map<string,string> env = system.getenv();
  //获取系统的所有环境变量
  for(string name : env.keyset()){
   system.out.println(name + " : " +env.get(name));
  }
  //获取系统的指定环境变量的值
  system.out.println(env.get("java_home"));

  //获取系统的所有属性
  properties prop = system.getproperties();
  //将系统的属性保存到配置文件中去
  prop.store(new fileoutputstream("prop.properties"),"system properties");
  //输出特定的系统属性
  system.out.println(system.getproperty("os.name"));
 }

2,与系统时间有关的方法操作
复制代码 代码如下:
public static void systime(){
  //获取系统当前的时间毫秒currenttimemillis()(返回当前时刻距离utc 1970.1.1 00:00的时间差)
  long time = system.currenttimemillis();
  system.out.println(time);

  long time1 = system.nanotime();//主要用于计算时间差单位纳秒
  long time3 = system.currenttimemillis();
  for(long i =0l ;i <999l; i++){}
  long time2 = system.nanotime();
  long time4 = system.currenttimemillis();
  system.out.println(time2 - time1+ " : " +(time4 - time3));
 }

3,鉴别两个对象在堆内存当中是否是同一个
复制代码 代码如下:
public static void identityhashcode(){
  //str1 str2为两个不同的string对象
  string str1 = new string("helloworld");
  string str2 = new string("helloworld");
  //由于string类重写了hashcode()方法 所以 他们的hashcode是一样的
  system.out.println(str1.hashcode()+" : "+str2.hashcode());
  //由于他们不是同一个对象所以他们的计算出来的hashcode时不同的。
  //实际上该方法使用的时最原始的hashcode计算方法即object的hashcode计算方法
  system.out.println(system.identityhashcode(str1) + " : "+ system.identityhashcode(str2));
  string str3 = "hello";
  string str4 = "hello";
  //由于他们引用的是常量池中的同一个对象 所以他们的hashcode是一样的
  system.out.println(system.identityhashcode(str3) + " : "+ system.identityhashcode(str4));
  /*输出如下
   -1554135584 : -1554135584
   28705408 : 6182315
   21648882 : 21648882
  */
 }

runtime类的常用用法
每个 java 应用程序都有一个 runtime 类实例,使应用程序能够与其运行的环境相连接。
复制代码 代码如下:
class runtimetest
{
 public static void main(string[] args) throws exception
 {
  getjvminfo();
  //exectest();
 }
 public static void getjvminfo(){
  //获取java运行时相关的运行时对象
  runtime rt = runtime.getruntime();
  system.out.println("处理器数量:" + rt.availableprocessors()+" byte");
  system.out.println("jvm总内存数 :"+ rt.totalmemory()+" byte");
  system.out.println("jvm空闲内存数: "+ rt.freememory()+" byte");
  system.out.println("jvm可用最大内存数: "+ rt.maxmemory()+" byte");
 }
 public static void exectest()throws exception{
  runtime rt = runtime.getruntime();
  //在单独的进程中执行指定的字符串命令。
  rt.exec("mspaint e:\\mmm.jpg");
 }
}

《System 类 和 Runtime 类的常用用法介绍.doc》

下载本文的Word格式文档,以方便收藏与打印。