System class in java is one of the core classes and I have never seen any java developer who doesn’t use it. One of the easiest way to log information for debugging is System.out.print() function. System class is final and all of it’s members and methods are static so that we can’t subclass and override it’s behavior through inheritance.

Java中的系统类是核心类之一,我从未见过任何不使用它的Java开发人员。 记录用于调试的信息的最简单方法之一是System.out.print()函数。 系统类是最终的,其所有成员和方法都是静态的,因此我们不能通过继承来继承和覆盖其行为。

(System Class in Java)

System class in java doesn’t provide any public constructors. So we can’t instantiate this class (for argument sake, we can instantiate it using Java Reflection) and that’s why all of it’s methods are static.

Java中的系统类不提供任何公共构造函数。 因此,我们无法实例化此类(出于参数考虑,我们可以使用Java Reflection实例化该类),这就是为什么其所有方法都是静态的。

Here we will look into the different features provided by java.lang.System class.

在这里,我们将研究java.lang.System类提供的不同功能。

  1. Java System Array Copy Java系统阵列复制
  2. Java System Properties Java系统属性
  3. Reading and Writing to Console 读写控制台
  4. Java System Get Current Time Java系统获取当前时间
  5. Java System Environment Variables Java系统环境变量
  6. Security Manager 安全经理
  7. File IO Operations 文件IO操作
  8. Miscellaneous Tasks 杂项任务

(Java System Array Copy)

Java System class provides a native method for copying data from one array to another. This is a native implementation and supposed to be faster than other ways to copy array data.

System array copy method throws IndexOutOfBoundsException if copying would cause access of data outside array bounds. It also throws ArrayStoreException if an element in the source array could not be stored into the destination array because of a type mismatch and NullPointerException

Below example program shows how to use this method.

int [] array1 = {1,2,3,4,5};
int[] array2 = {10,20,30,40,50};
		
//copying first two elements from array1 to array2 starting from index 2 of array2
System.arraycopy(array1, 0, array2, 2, 2);
		
System.out.println(Arrays.toString(array2)); //prints "[10, 20, 1, 2, 50]"

Java System类提供了一种将数据从一个数组复制到另一个数组的本机方法。 这是本机实现,应该比其他复制阵列数据的方法快。

如果复制会导致超出数组范围的数据访问,则系统数组复制方法将抛出IndexOutOfBoundsException 。 如果由于类型不匹配而无法将源数组中的元素存储到目标数组中,则还会引发ArrayStoreException如果源数组或目标数组为null,则抛出NullPointerException

下面的示例程序显示了如何使用此方法。

int [] array1 = {1,2,3,4,5};
int[] array2 = {10,20,30,40,50};
		
//copying first two elements from array1 to array2 starting from index 2 of array2
System.arraycopy(array1, 0, array2, 2, 2);
		
System.out.println(Arrays.toString(array2)); //prints "[10, 20, 1, 2, 50]"

(Java System Properties)

System class contains useful method to get the list of System properties, get specific property, set system property and clear any existing property. The sample program below shows different methods and it’s usage.

//Get System Defined Properties
Properties systemProps = System.getProperties();
Set<Object> keySet = systemProps.keySet();
for(Object obj : keySet){
	String key = (String) obj;
	System.out.println("{"+obj+"="+systemProps.getProperty(key)+"}");
}

//Get Specific Property
System.out.println(System.getProperty("user.country"));

//Clear property example
System.clearProperty("user.country");
System.out.println(System.getProperty("user.country")); //print null

//Set System property
System.setProperty("user.country", "IN");
System.out.println(System.getProperty("user.country")); //prints "IN"

If we run above code in a java program, we get following output. Notice that output will vary based on your system configurations.

Check out Java Properties

系统类包含有用的方法来获取系统属性列表,获取特定属性,设置系统属性并清除任何现有属性。 下面的示例程序显示了不同的方法及其用法。

如果在Java程序中运行以上代码,则会得到以下输出。 请注意,输出将根据您的系统配置而有所不同。

{java.runtime.name=Java(TM) SE Runtime Environment}
{sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib}
{java.vm.version=23.5-b02}
{gopherProxySet=false}
{java.vm.vendor=Oracle Corporation}
{java.vendor.url=https://java.oracle.com/}
{path.separator=:}
{java.vm.name=Java HotSpot(TM) 64-Bit Server VM}
{file.encoding.pkg=sun.io}
{user.country=US}
{sun.java.launcher=SUN_STANDARD}
{sun.os.patch.level=unknown}
{java.vm.specification.name=Java Virtual Machine Specification}
{user.dir=/Users/pankaj/CODE/MyProject}
{java.runtime.version=1.7.0_09-b05}
{java.awt.graphicsenv=sun.awt.CGraphicsEnvironment}
{java.endorsed.dirs=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/endorsed}
{os.arch=x86_64}
{java.io.tmpdir=/var/folders/f1/25ry1vy5675_30mkwqp7p46r0000gn/T/}
{line.separator=
}
{java.vm.specification.vendor=Oracle Corporation}
{os.name=Mac OS X}
{sun.jnu.encoding=US-ASCII}
{java.library.path=/Users/pankaj/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.}
{java.specification.name=Java Platform API Specification}
{java.class.version=51.0}
{sun.management.compiler=HotSpot 64-Bit Tiered Compilers}
{os.version=10.8.3}
{http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16}
{user.home=/Users/pankaj}
{user.timezone=}
{java.awt.printerjob=sun.lwawt.macosx.CPrinterJob}
{file.encoding=MacRoman}
{java.specification.version=1.7}
{java.class.path=/Users/pankaj/CODE/bin:/Users/pankaj/}
{user.name=pankaj}
{java.vm.specification.version=1.7}
{sun.java.command=com.journaldev.util.SystemClassExamples}
{java.home=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre}
{sun.arch.data.model=64}
{user.language=en}
{java.specification.vendor=Oracle Corporation}
{awt.toolkit=sun.lwawt.macosx.LWCToolkit}
{java.vm.info=mixed mode}
{java.version=1.7.0_09}
{java.ext.dirs=/Users/pankaj/Library/Java/Extensions:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/ext:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java}
{sun.boot.class.path=/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/sunrsasign.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/lib/JObjC.jar:/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home/jre/classes}
{java.vendor=Oracle Corporation}
{file.separator=/}
{java.vendor.url.bug=https://bugreport.sun.com/bugreport/}
{sun.io.unicode.encoding=UnicodeBig}
{sun.cpu.endian=little}
{socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16}
{ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16}
{sun.cpu.isalist=}
US
null
IN

查看Java属性示例教程。

(Reading and Writing to Console)

Java System Class provide a method to get the unique Console object associated with the running JVM.

Console class was introduced in Java IO

If no console is associated with the current JVM, for example running through Eclipse or running as background program, then it returns null.

Below sample program show get Console object from System class and use it.

Console console = System.console();

if(console != null){
    Calendar c = new GregorianCalendar();
    console.printf("Welcome %1$s%n", "Pankaj"); //prints "Welcome Pankaj"
    console.printf("Current time is: %1$tm %1$te,%1$tY%n", c); //prints "Current time is: 08 5,2013"
    console.flush();
} else{
	//No console is attached when run through Eclipse, background process
	System.out.println("No Console attached");
}

Java系统类提供了一种获取与正在运行的JVM相关联的唯一Console对象的方法。

控制台类是Java IO在1.6中引入的,它提供了有用的方法来安全地打印格式化的数据和读取密码。

如果没有控制台与当前JVM关联,例如通过Eclipse运行或作为后台程序运行,则它将返回null。

下面的示例程序显示了从System类获取Console对象并使用它。

(java System Get Current Time)

System class in java provide two methods to get the current time in milliseconds and nano time.

We can use time in milliseconds to create Date object, nano time is used mostly in scientific experiments or in benchmark testing.

Below code snippet show the usage of System class methods to get time related information.

long currentTimeMillis = System.currentTimeMillis();
Date date = new Date(currentTimeMillis);
System.out.println("Current time in millis="+currentTimeMillis);
System.out.println(date); //prints 2013-08-05

long nanoTime = System.nanoTime();
System.out.println("Current nano time="+nanoTime);

Java中的系统类提供了两种方法来获取当前时间(以毫秒为单位)和纳秒级时间。

我们可以使用毫秒为单位的时间来创建Date对象,纳米时间主要用于科学实验或基准测试中。

下面的代码片段显示了如何使用System类方法获取与时间相关的信息。

long currentTimeMillis = System.currentTimeMillis();
Date date = new Date(currentTimeMillis);
System.out.println("Current time in millis="+currentTimeMillis);
System.out.println(date); //prints 2013-08-05

long nanoTime = System.nanoTime();
System.out.println("Current nano time="+nanoTime);

(Java System Environment Variables)

Java System class provides a method to get the environment variables data in Map form, the returned Map is unmodifiable and it contains key-value pairs in String object.

//get unmodifiable environment variables map
Map<String, String> envMap = System.getenv();
Set<String> keySet = envMap.keySet();
for(String key : keySet){
	System.out.println("Key="+key+",value="+envMap.get(key));
}

//Get Specific environment variable
String pathValue = System.getenv("PATH");
System.out.println("$PATH="+pathValue);

Java System类提供了一种以Map形式获取环境变量数据的方法,返回的Map是不可修改的,并且在String对象中包含键值对。

//get unmodifiable environment variables map
Map<String, String> envMap = System.getenv();
Set<String> keySet = envMap.keySet();
for(String key : keySet){
	System.out.println("Key="+key+",value="+envMap.get(key));
}

//Get Specific environment variable
String pathValue = System.getenv("PATH");
System.out.println("$PATH="+pathValue);

(Security Manager)

SecurityManager class is used to implement security policy for applications, System class provide useful methods to get SecurityManager for the currently running JVM and to set the SecurityManager for the application.

SecurityManager secManager = System.getSecurityManager();
if(secManager == null){
	System.out.println("SecurityManager is not configured");
}
SecurityManager mySecManager = new SecurityManager();
System.setSecurityManager(mySecManager);
secManager = System.getSecurityManager();
if(secManager != null){
	System.out.println("SecurityManager is configured");
}

SecurityManager类用于实现应用程序的安全策略,System类提供有用的方法来获取当前运行的JVM的SecurityManager并为应用程序设置SecurityManager。

SecurityManager secManager = System.getSecurityManager();
if(secManager == null){
	System.out.println("SecurityManager is not configured");
}
SecurityManager mySecManager = new SecurityManager();
System.setSecurityManager(mySecManager);
secManager = System.getSecurityManager();
if(secManager != null){
	System.out.println("SecurityManager is configured");
}

(File IO Operations)

System class contains three fields – in, out and err. They are used to read data from InputStream and to write data to OutputStream.

System class provide methods to set different types of InputStream and OutputStream to be used for logging purposes.

For example, we can set FileOutputStream to out and err fields so that console output is written to file.

Below code snippet shows the usage of these fields and how can we set them using setter methods.

try(FileInputStream fis = new FileInputStream("input.txt");
	FileOutputStream fos = new FileOutputStream("server.log");) {

//set input stream
System.setIn(fis);
char c = (char) System.in.read();
System.out.print(c); //prints the first character from input stream

//set output stream
System.setOut(new PrintStream(fos));
System.out.write("Hi Pankaj\n".getBytes());

//set error stream
System.setErr(new PrintStream(fos));
System.err.write("Exception message\n".getBytes());
} catch (IOException e) {
	e.printStackTrace();
}

Notice the use of Java 7 try with resources feature in above try-block.

系统类包含三个字段-in,out和err。 它们用于从InputStream读取数据并将数据写入OutputStream 。

系统类提供了用于设置用于记录目的的不同类型InputStream和OutputStream的方法。

例如,我们可以将FileOutputStream设置为out和err字段,以便将控制台输出写入文件。

下面的代码片段显示了这些字段的用法,以及如何使用setter方法设置它们。

注意,在上面的try-block中使用了Java 7 try with resources功能。

(Miscellaneous Tasks)

System class provides some other methods for miscellaneous tasks. For example, to run Garbage Collector, load external libraries, map the library name to OS specific String, run the finalize method for any object waiting for finalization and to terminate the JVM.

//run the garbage collector
System.gc();
System.out.println("Garbage collector executed.");

//map library name
String libName = System.mapLibraryName("os.name");
System.out.println("os.name library="+libName);

//load external libraries
System.load("lixXYZ.so");
System.loadLibrary("libos.name.dylib");

//run finalization
System.runFinalization();

//terminates the currently running JVM
System.exit(1);
// this line will never print because JVM is terminated
System.out.println("JVM is terminated");

系统类提供了一些其他方法来执行杂项任务。 例如,要运行Garbage Collector,加载外部库,将库名称映射到特定于OS的String,为等待完成的任何对象运行finalize方法并终止JVM。

That’s all about System class in java, I hope it will help you in getting most out of java System class.

这就是关于Java中的System类的所有信息,希望它能帮助您充分利用java System类。

Reference: API Doc

参考: API文档