System类代表当前Java程序的运行平台,程序不能创建System类的对象, System类 提供了一些类变量和类方法,允许直接通过System类来调用这些类变量和类方法。
常用方法:
例子:
public class dome {
@Test
public void test(){
// System.out 标准输出
// System.err 错误输出
// System.in 标准输入
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext()){
String str=scanner.next();
//中文转为UTF-8
byte[] bs= str.getBytes(Charset.forName("GBK"));
String str1=new String(bs,Charset.forName("UTF-8"));
System.out.println(str1);
//判断让它结束 尾加<0>后缀回车结束循环
if (str1.endsWith("<0>")) {
break;
}
}
System.out.println("-----------------------------------------");
// 获取系统所有的环境变量
System.out.println("系统所有的环境变量");
Map<String, String> map = System.getenv();
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + "--->" + map.get(key));
}
System.out.println("-----------------------------------------");
System.out.println("获取指定的系统变量");
//获取指定的系统变量 JAVA_HOME
System.out.println(System.getenv("JAVA_HOME"));
System.out.println("-----------------------------------------");
System.out.println("获取系统属性");
// 获取系统属性
System.out.println(System.getProperties());
System.out.println("获取指定系统属性");
System.out.println(System.getProperty("user.name"));
// gc() 函数的作用只是提醒虚拟机:希望进行一次垃圾回收。
// 但是它不能保证垃圾回收一定会进行,而且具体什么时候进行是取决于具体的虚拟机的,不同的虚拟机有不同的对策。
System.gc();
System.out.println("-----------------------------------------");
System.out.println("----currentTimeMillis和nanoTime----");
// 返回当前时间与UTC 1970年1月1日午夜的时间差
System.out.println(System.currentTimeMillis());//毫秒单位
// nanoTime 纳秒 1毫秒(ms)=1000000纳秒(ns)
System.out.println(System.nanoTime());
//运行速度 返回10次不同的时间
for (int i = 0; i < 10; i++) {
System.out.println(System.currentTimeMillis() + "<>"
+ System.nanoTime());
}
System.out.println("-----------------------------------------");
System.out.println("----identityHashCode----");
// identityHashCode 返回指定对象的精确hashCode值,
// 下面程序中str1和str2是两个不同对象
String str1 = new String("Hello,World");
String str2 = new String("Hello,World");
// String重写了hashCode()方法——改为根据字符序列计算hashCode值,
// 因为str1和str2的字符序列相同,所以它们的hashCode方法返回值相同
System.out.println(str1.hashCode() + "\t" + str2.hashCode());//-518995464 -518995464
// str1和str2是不同的字符串对象,所以它们的identityHashCode值不同
System.out.println(System.identityHashCode(str1) + "\t"
+ System.identityHashCode(str2));//1398811002 1401235114
String str3 = "Hello,World";// 字符串常量池
String str4 = "Hello,World"; //与上区别 new了路途不同所有哈希值不同
// str3和str4是相同的字符串对象,所以它们的identityHashCode值相同
System.out.println(System.identityHashCode(str3) + "\t"
+ System.identityHashCode(str4));//1252887996 1252887996
// exit 停止正在运行的虚拟机,退出程序
System.exit(0); //0状态随便给 异常可以给负数 就无法打印下面方法
System.out.println("这一句将不会打印出来,因为没有执行");
}
}
打印结果: