1类签名与注释
public final class System
System类包含一些有用的类属性和方法。该类不能被实例化,所以其所有属性与方法都是static的。
2标准输入输出流
public final static InputStream in = null; public final static PrintStream out = null;
标准输入输出流会在initializeSystemClass方法中被初始化。
(1)控制台输入输出1
1 Scanner in = new Scanner(System.in); 2 System.out.println(in.nextLine());
代码在运行到第1行的时候会等待用户在控制台输入,然后接下来通过out的println方法在控制台输出。
(2)控制台输入输出2
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { String str = in.readLine(); System.out.println(str); } catch (IOException e) { e.printStackTrace(); }
3数组复制
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
arraycopy是一个native方法。作用是将src数组里的值复制到dest数组中去。下面是其详细用法:
1 int[] a = {0,1,2}; 2 int[] b = {3,4,5}; 3 int[] ab = new int[a.length+b.length]; 4 5 System.arraycopy(a, 0, ab, 0, a.length); 6 for(int i:ab){ 7 System.out.print(i+" "); 8 } 9 System.out.println(""); 10 11 System.arraycopy(b, 0, ab, a.length, b.length); 12 for(int i:ab){ 13 System.out.print(i+" "); 14 }
输出为
0 1 2 0 0 0 0 1 2 3 4 5
line5表示将数组a从0开始复制到数组ab也是从0开始,复制的长度是a的长度。也就是说ab[0] = a[0] = 0依此类推ab[2] = a[2] = 2。所以第一次复制后ab数组为{0,1,2,0,0,0},前面三位是a复制过来的,后面三个0是其初始化时的默认值。同理,line11也很好理解了。
4其他常用方法
(1)currentTimeMillis
public static native long currentTimeMillis();
该方法的作用是返回当前的计算机时间,时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。
可以直接把这个方法强制转换成date类型。
long currentTime = System.currentTimeMillis(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒"); Date date = new Date(currentTime); System.out.println(formatter.format(date));
输出:2018年-05月08日-09时58分45秒
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒"); Date date = new Date(); System.out.println(formatter.format(date));
上面两段代码某种程度上是一样的,但是我们可以用变量currentTime保存某一刻的时间,然后再格式刷出来。而直接new date只能获取当前时间。
(2)exit
public static void exit(int status) { Runtime.getRuntime().exit(status); }
status为0表示正常退出,其他值表示异常退出。可以在异常catch块中System.exit(1)来异常退出。
(3)gc
public static void gc() { Runtime.getRuntime().gc(); }
该方法会通知jvm进行垃圾回收,但是jvm不一定会马上处理。
(4)runFinalization
public static void runFinalization() { Runtime.getRuntime().runFinalization(); }
强制调用已经失去引用的对象的finalize方法。
(5)Properties
System类里面包含一套对Properties的操作,包括getProperties与setProperties等。在initializeSystemClass初始化方法中会默认初始化Properties。简单使用方法如下:
//获取当前操作系统 String osName = System.getProperty("os.name"); System.out.println(osName); //添加自己的属性 Properties pro = System.getProperties(); pro.put("ouym", "24"); System.out.println(System.getProperty("ouym"));
完