System类的构造方法是private,所以不能创建它的对象。其内部的成员变量和方法都是static的,可以调用。成员变量有:
- PrintStream out 标准输出流,如println就是out的方法,不是System的方法
- InputStream in 标准输入流
- PrintStream err 标准错误输出流
public void contextLoads() {
int c;
try {
// 使用System.in的话读汉字会出错,用InputStreamReader
// 并指定编码集才可以
c = System.in.read();
//InputStreamReader in = new InputStreamReader(System.in, "UTF-8");
//c = in.read();
while (c != '\r') {
System.out.print((char) c);
//c = in.read();
c = System.in.read();
}
} catch(IOException e) {
System.out.println("\nThis is IOException: \n");
System.out.println(e.toString());
} finally {
System.out.println("\nThis is finally bloc: \n");
System.err.println();
}
}
常用方法
数组复制
arraycopy方法:从原数组中截取一段,替换到目标数组中
System.arraycopy(dataType[] srcArray,int srcIndex,dataType[] destArray,int destIndex,int length)
此方法要求srcIndex+length <= srcArray.length且destIndex+length <= destArray.length
如果目标数组存在,不会重构,相当于替换部分元素。
System.arraycopy(scores,0,newScores,2,8);
//这里表示使用scores数组的[0,8)替换newScores数组的[2, 10)
获取当前时间
long start=System.currentTimeMillis();
// code block
long end = System.currentTimeMillis();
double time=(end-start) / 1000.0;
// 因为获取的都是毫秒,要除以1000换算到秒
终止当前运行的虚拟机
public static void exit(int status)
status为0时表示正常退出,非0时是异常。可在图形界面编程中实现程序的退出功能。
获取系统级参数
System.getProperty(属性名);
举例:
System.out.println(System.getProperty("java.version"));
System.out.println(System.getProperty("java.home"));
System.out.println(System.getProperty("os.name"));
System.out.println(System.getProperty("os.version"));
System.out.println(System.getProperty("user.name"));
System.out.println(System.getProperty("user.home"));
System.out.println(System.getProperty("user.dir")); // 打印项目的根目录
System.out.println(System.getProperty("file.separator")); // linux和win是不同的路径分隔符,这里会根据系统产生对应的符号