说明
System 类代表当前 Java 程序的运行平台,程序不能创建 System 类的对象,System 类提供了一些类的变量和方法,允许直接通过 System 类来调用这些类变量和方法。
System 类提供了代表标准输入、输出和错误输出的类变量,并且提供了一些静态方法用于访问环境变量、系统变量属性的方法,还提供了加载文件和动态链接库的方法。
System 类实战
标准的输出
在 System 类里面为了支持 I/O 操作,专门提供了三个常量:
- 错误输出:
public static final PrintStream err;
- System.err 是 PrintStream 类对象,此对象专门负责进行错误信息的输出操作。
- 输出到标准输出设备(显示器):
public static final PrintStream out;
- System.out 是专门准备的支持屏幕输出信息的操作对象。
- 从标准输入设备读取(键盘):
public static final PrintStream in;
// 标准输出
System.out.println();
// 错误刘输出
System.err.println();
键盘输入操作
import java.io.InputStream;
public class Demo {
public static void main(String[] args) throws Exception {// 此处直接抛错
InputStream in = System.in;
System.out.println("请输入:");
int temp = 0;
int foot = 0;
byte[] data = new byte[1024];
while ((temp = in.read()) != -1) {
data[foot++] = (byte) temp;
// 输出回车结束
if (temp == '\n') {
break;
}
}
System.out.println("输入的内容是:" + new String(data, 0, foot));
}
}
统计一个程序消耗的时间
主要是通过 System.currentTimeMillis()
获取到当前的系统时间,然后进行比较
public class SystemTest {
public static void main(String[] args) {
long start = System.currentTimeMillis();
String str = "";
for (int i = 0; i < 20000; i++) {
str += i;
}
long end = System.currentTimeMillis();
System.out.println("消耗的时间是:" + (end - start));
}
}
数组拷贝
public class Demo {
public static void main(String[] args) throws Exception {
int[] num = new int[] { 55, 77, 22, 88, 99 };
int[] temp = new int[4];
System.arraycopy(num, 0, temp, 0, 4);
for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
}
}
finalize方法
在 System 类中定义了一个操作方法:public static void gc()
,这个 gc() 方法并不是新的概念,而是最终也是会调用 Runtime 类中的 gc() 方法。
class Book{
public Book(){
System.out.println("新建 Book 类");
}
// 覆写 Object 类中的 finalize
@Override
protected void finalize() throws Throwable {
System.out.println("新建 Book 类被销毁了。。。");
}
}
public class SystemTest {
public static void main(String[] args) {
Book book = new Book();
// 将初始化的 book 类设置为 null
book = null;
System.gc(); // 垃圾回收
}
}
final、finally、finalize 的区别
- final:关键字,定义不能被继承的类、不能被覆写的方法、常量;
- finally:关键字,异常的统一出口;
- finalize:方法,Object 类提供的方法(protected void finalize throws Throwable),指的是对象回收前的收尾操作方法,即使出现了异常也不会导致程序中断执行。