System 类提供的设施包括标准输入、标准输出和错误输出流;访问外部定义的属性和环境变量;加载文件和库的方法;以及一种用于快速复制数组的一部分的实用方法。它扩展了对象类。
领域:
- 公共静态最终InputStream:“standard” 输入流。该流已打开并准备好提供输入数据。通常,该流对应于键盘输入或主机环境或用户指定的另一个输入源。
- 公共静态最终PrintStream输出:“standard” 输出流。该流已打开并准备好接受输出数据。通常,该流对应于显示输出或由主机环境或用户指定的另一个输出目的地。
- 公共静态最终PrintStream错误:“standard” 错误输出流。该流已打开并准备好接受输出数据。
通常,该流对应于显示输出或由主机环境或用户指定的另一个输出目的地。按照惯例,此输出流用于显示错误消息或其他应引起用户立即注意的信息,即使主要输出流(变量 out 的值)已重定向到文件或其他目标通常不会连续监测。
方法:
1. static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size):复制数组。要复制的数组在 source 中传递,并且在 sourceStart 中传递在 source 中开始复制的索引。将接收副本的数组在 target 中传递,并且在 targetStart 中传递副本将在目标内开始的索引。 Size 是复制的元素数量。
Syntax: public static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size) Returns: NA. Exception: IndexOutOfBoundsException - if copying would cause access of data outside array bounds. ArrayStoreException - if an element in the source array could not be stored into the target array because of a type mismatch. NullPointerException - if either source or target is null.
Java
// Java code illustrating arraycopy() method
import java.lang.*;
import java.util.Arrays;
class SystemDemo
{
public static void main(String args[])
{
int[] a = {1, 2, 3, 4, 5};
int[] b = {6, 7, 8, 9, 10};
System.arraycopy(a, 0, b, 2, 2);
// array b after arraycopy operation
System.out.println(Arrays.toString(b));
}
}
输出:
[6, 7, 1, 2, 10]
2. static StringclearProperty(String key):删除指定键指示的系统属性。
Syntax: public static String clearProperty(String key) Returns: the previous string value of the system property, or null if there was no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty.
3. static String getProperty(String key):获取指定key指示的系统属性。
Syntax: public static String getProperty(String key) Returns: the string value of the system property, or null if there is no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty.
4. static String getProperty(String key, String def):获取指定key指示的系统属性。
Syntax: public static String getProperty(String key, String def) Returns: the string value of the system property, or the default value if there is no property with that key. Exception: SecurityException - if a security manager exists and its checkPropertyAccess method doesn't allow access to the specified system property. NullPointerException - if key is null. IllegalArgumentException - if key is empty.
5. static String setProperty(String key, String value):设置指定键指示的系统属性。
Syntax: public static String setProperty(String key, String value) Returns: the previous value of the system property, or null if it did not have one. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow setting of the specified property. NullPointerException - if key or value is null. IllegalArgumentException - if key is empty.
Java
// Java code illustrating clearProperty(), getProperty()
// and setProperty() methods
import java.lang.*;
import static java.lang.System.clearProperty;
import static java.lang.System.setProperty;
import java.util.Arrays;
class SystemDemo
{
public static void main(String args[])
{
// checking specific property
System.out.println(System.getProperty("user.home"));
// clearing this property
clearProperty("user.home");
System.out.println(System.getProperty("user.home"));
// setting specific property
setProperty("user.country", "US");
// checking property
System.out.println(System.getProperty("user.country"));
// checking property other than system property
// illustrating getProperty(String key, String def)
System.out.println(System.getProperty("user.password",
"none of your business"));
}
}
输出:
/Users/abhishekverma null US none of your business
6. static Console console():返回与当前Java虚拟机关联的唯一Console对象(如果有)。
Syntax: public static Console console() Returns: The system console, if any, otherwise null. Exception: NA
Java
// Java code illustrating console() method
import java.io.Console;
import java.lang.*;
import java.util.Currency;
import java.util.Locale;
class SystemDemo
{
public static void main(String args[]) throws NullPointerException
{
Console c = System.console();
if(c != null)
{
Currency currency = Currency.getInstance(Locale.ITALY);
c.printf(currency.getSymbol());
c.flush();
}
else
System.out.println("No console attached");
}
}
输出:
No console attached
7. static long currentTimeMillis():返回当前时间(以毫秒为单位)。请注意,虽然返回值的时间单位是毫秒,但该值的粒度取决于底层操作系统,并且可能会更大。例如,许多操作系统以数十毫秒为单位测量时间。
Syntax: public static long currentTimeMillis() Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. Exception: NA.
8. static long nanoTime():返回正在运行的Java虚拟机的high-resolution时间源的当前值,以纳秒为单位。
Syntax: public static long nanoTime() Returns: the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds Exception: NA
Java
// Java code illustrating currentTimeMillis() method
import java.lang.*;
class SystemDemo
{
public static void main(String args[]) throws NullPointerException
{
System.out.println("difference between the "
+ "current time and midnight,"
+ " January 1, 1970 UTC is: " +
System.currentTimeMillis());
System.out.println("current time in "
+ "nano sec: " +
System.nanoTime());
}
}
输出:
difference between the current time and midnight, January 1, 1970 UTC is: 1499520649545 current time in nano sec: 29976939759226
9.静态无效退出(int状态):终止当前正在运行的 Java 虚拟机。该参数用作状态代码;按照惯例,非零状态代码表示异常终止。
该方法调用Runtime类中的exit方法。此方法永远不会正常返回。
调用 System.exit(n) 实际上等同于以下调用:
运行时.getRuntime().exit(n)
Syntax: public static void exit(int status) Returns: NA Exception: SecurityException - if a security manager exists and its checkExit method doesn't allow exit with the specified status.
Java
// Java code illustrating exit() method
import java.lang.*;
class SystemDemo
{
public static void main(String args[]) throws NullPointerException
{
System.gc();
System.out.println("Garbage collector executed ");
System.out.println(System.getProperty("os.name"));
System.exit(1);
// this line will not execute as JVM terminated
System.out.println("JVM terminated");
}
}
输出:
Garbage collector executed Mac OS X
10. static void gc():运行垃圾Collector。调用 gc 方法表明 Java 虚拟机将努力回收未使用的对象,以使它们当前占用的内存可供快速重用。当控制权从方法调用返回时,Java 虚拟机已尽最大努力从所有丢弃的对象中回收空间。
Syntax: public static void gc() Returns: NA Exception: NA
Java
// Java code illustrating gc() method
import java.lang.*;
class SystemDemo
{
public static void main(String args[])
{
Runtime gfg = Runtime.getRuntime();
long memory1, memory2;
Integer integer[] = new Integer[1000];
// checking the total memory
System.out.println("Total memory is: "
+ gfg.totalMemory());
// checking free memory
memory1 = gfg.freeMemory();
System.out.println("Initial free memory: "
+ memory1);
// calling the garbage collector on demand
System.gc();
memory1 = gfg.freeMemory();
System.out.println("Free memory after garbage "
+ "collection: " + memory1);
// allocating integers
for (int i = 0; i < 1000; i++)
integer[i] = new Integer(i);
memory2 = gfg.freeMemory();
System.out.println("Free memory after allocation: "
+ memory2);
System.out.println("Memory used by allocation: " +
(memory1 - memory2));
// discard integers
for (int i = 0; i < 1000; i++)
integer[i] = null;
System.gc();
memory2 = gfg.freeMemory();
System.out.println("Free memory after "
+ "collecting discarded Integers: " + memory2);
}
}
输出:
Total memory is: 128974848 Initial free memory: 126929976 Free memory after garbage collection: 128632160 Free memory after allocation: 127950520 Memory used by allocation: 681640 Free memory after collecting discarded Integers: 128643472
11.静态Mapgetenv():返回当前系统环境的不可修改的字符串映射视图。环境是一个依赖于系统的从名称到值的映射,该映射从父进程传递到子进程。
如果系统不支持环境变量,则返回空映射。
Syntax: public static Map getenv() Returns: the environment as a map of variable names to values. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow access to the process environment
12. static String getenv(字符串名称):获取指定环境变量的值。环境变量是依赖于系统的外部命名值。
系统属性和环境变量在概念上都是名称和值之间的映射。这两种机制都可用于将用户定义的信息传递给 Java 进程。环境变量具有更全局的影响,因为它们对定义它们的进程的所有后代都可见,而不仅仅是直接的 Java 子进程。它们在不同的操作系统上可能具有细微不同的语义,例如不区分大小写。由于这些原因,环境变量更有可能产生意想不到的副作用。最好尽可能使用系统属性。当需要全局效果或外部系统接口需要环境变量(例如 PATH)时,应使用环境变量。
Syntax: public static String getenv(String name) Returns: the string value of the variable, or null if the variable is not defined in the system environment. Exception: NullPointerException - if name is null SecurityException - if a security manager exists and its checkPermission method doesn't allow access to the environment variable name.
Java
// Java code illustrating getenv() method
import java.lang.*;
import java.util.Map;
import java.util.Set;
class SystemDemo
{
public static void main(String args[])
{
Map<String, String> gfg = System.getenv();
Set<String> keySet = gfg.keySet();
for(String key : keySet)
{
System.out.println("key= " + key);
}
// checking specific environment variable
System.out.println(System.getenv("PATH"));
}
}
输出:
key= JAVA_MAIN_CLASS_5396 key= PATH key= J2D_PIXMAPS key= SHELL key= USER key= TMPDIR key= SSH_AUTH_SOCK key= XPC_FLAGS key= LD_LIBRARY_PATH key= __CF_USER_TEXT_ENCODING key= Apple_PubSub_Socket_Render key= LOGNAME key= LC_CTYPE key= XPC_SERVICE_NAME key= PWD key= JAVA_MAIN_CLASS_2336 key= SHLVL key= HOME key= _ /usr/bin:/bin:/usr/sbin:/sbin
13. static Properties getProperties():确定当前系统属性。
Syntax: public static Properties getProperties() Returns: the system properties. Exception: SecurityException - if a security manager exists and its checkPropertiesAccess method doesn't allow access to the system properties.
Java
// Java code illustrating getProperties() method
import java.lang.*;
import java.util.Properties;
import java.util.Set;
class SystemDemo
{
public static void main(String args[])
{
Properties gfg = System.getProperties();
Set<Object> keySet = gfg.keySet();
for(Object key : keySet)
{
System.out.println("key= " + key);
}
}
}
输出:
key= java.runtime.name key= sun.boot.library.path key= java.vm.version key= user.country.format key= gopherProxySet key= java.vm.vendor key= java.vendor.url key= path.separator key= java.vm.name key= file.encoding.pkg key= user.country key= sun.java.launcher key= sun.os.patch.level key= java.vm.specification.name key= user.dir key= java.runtime.version key= java.awt.graphicsenv key= java.endorsed.dirs key= os.arch key= java.io.tmpdir key= line.separator key= java.vm.specification.vendor key= os.name key= sun.jnu.encoding key= java.library.path key= java.specification.name key= java.class.version key= sun.management.compiler key= os.version key= http.nonProxyHosts key= user.home key= user.timezone key= java.awt.printerjob key= file.encoding key= java.specification.version key= java.class.path key= user.name key= java.vm.specification.version key= sun.java.command key= java.home key= sun.arch.data.model key= user.language key= java.specification.vendor key= awt.toolkit key= java.vm.info key= java.version key= java.ext.dirs key= sun.boot.class.path key= java.vendor key= file.separator key= java.vendor.url.bug key= sun.io.unicode.encoding key= sun.cpu.endian key= socksNonProxyHosts key= ftp.nonProxyHosts key= sun.cpu.isalist
14.静态SecurityManager getSecurityManager():获取系统安全接口。
Syntax: static SecurityManager getSecurityManager() Returns: if a security manager has already been established for the current application, then that security manager is returned; otherwise, null is returned. Exception: NA
15.静态无效setSecurityManager(SecurityManager s):设置系统安全性。
Syntax: public static void setSecurityManager(SecurityManager s) Returns: NA. Exception: SecurityException - if the security manager has already been set and its checkPermission method doesn't allow it to be replaced.
Java
// Java code illustrating setSecurityManager()
// and getSecurityManager() method
import java.lang.*;
class SystemDemo
{
public static void main(String args[])
{
SecurityManager gfg = new SecurityManager();
// setting the security manager
System.setSecurityManager(gfg);
gfg = System.getSecurityManager();
if(gfg != null)
System.out.println("Security manager is configured");
}
}
输出:
Security manager is configured
16. static void setErr(PrintStream err):重新分配“standard”错误输出流。
Syntax: public static void setErr(PrintStream err) Returns: NA Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard error output stream.
17. static void setIn(InputStream in):重新分配“standard”输入流。
Syntax: public static void setIn(InputStream in) Returns: NA. Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard input stream.
18. static void setOut(PrintStream out):重新分配“standard”输出流。
Syntax: public void setOut(PrintStream out) Returns: NA Exception: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard output stream.
Java
// Java code illustrating setOut(), setIn() and setErr() method
import java.lang.*;
import java.util.Properties;
import java.io.*;
class SystemDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream IN = new FileInputStream("input.txt");
FileOutputStream OUT = new FileOutputStream("system.txt");
// set input stream
System.setIn(IN);
char c = (char) System.in.read();
System.out.print(c);
// set output stream
System.setOut(new PrintStream(OUT));
System.out.write("Hi Abhishek\n".getBytes());
// set error stream
System.setErr(new PrintStream(OUT));
System.err.write("Exception message\n".getBytes());
}
}
输出:上述java代码的输出取决于“input.txt”文件中的内容。
创建您自己的“input.txt”,然后运行代码并检查输出。
19. static void load(String filename):从本地文件系统加载指定文件名的代码文件作为动态库。文件名参数必须是完整的路径名。
Syntax: public static void load(String filename) Returns: NA Exception: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic library UnsatisfiedLinkError - if the file does not exist. NullPointerException - if filename is null
20. static void loadLibrary(String libname):加载libname参数指定的系统库。库名称映射到实际系统库的方式取决于系统。
Syntax: public static void loadLibrary(String libname) Returns: NA Exception: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic library UnsatisfiedLinkError - if the library does not exist. NullPointerException - if libname is null
21. static String mapLibraryName(String libname):将库名称映射到表示本机库的特定于平台的字符串。
Syntax: public static String mapLibraryName(String libname) Returns: a platform-dependent native library name. Exception: NullPointerException - if libname is null
22. static void runFinalization():运行任何待终结的对象的终结方法。调用此方法表明 Java 虚拟机将努力运行那些已发现已被丢弃但尚未运行 Finalize 方法的对象的 Finalize 方法。当控制权从方法调用返回时,Java 虚拟机已尽最大努力完成所有未完成的终结。
Syntax: public static void runFinalization() Returns: NA Exception: NA.
Java
// Java code illustrating runFinalization(), load()
// loadLibrary() and mapLibraryName() method
import java.lang.*;
class SystemDemo
{
public static void main(String args[]) throws NullPointerException
{
// 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();
}
}
输出:
os.name library= libos.name.dylib
23. static int IdentityHashCode(Object x):为给定对象返回与默认方法hashCode()返回的哈希码相同的哈希码,无论给定对象的类是否覆盖hashCode()。空引用的哈希码为零。
Syntax: public static int identityHashCode(Object x) Returns: the hashCode. Exception: NA.
24. static Channel inheritedChannel():返回从创建此Java虚拟机的实体继承的通道。
Syntax: public static Channel inheritedChannel(). Returns: inherited channel, if any, otherwise null. Exception: IOException - If an I/O error occurs SecurityException - If a security manager is present and it does not permit access to the channel.
25. static String lineSeparator():返回系统相关的行分隔符字符串。它始终返回相同的值 - 系统属性行分隔符的初始值。
Syntax: public static String lineSeparator() Returns: On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n". Exception: NA
Java
// Java code illustrating lineSeparator(), inherentChannel()
// and identityHashCode() method
import java.io.IOException;
import java.lang.*;
import java.nio.channels.Channel;
class SystemDemo
{
public static void main(String args[])
throws NullPointerException,
IOException
{
Integer x = 400;
System.out.println(System.identityHashCode(x));
Channel ch = System.inheritedChannel();
System.out.println(ch);
System.out.println(System.lineSeparator());
}
}
输出:
1735600054 null "\r\n"
相关用法
- Java Java.lang.System.arraycopy()用法及代码示例
- Java Java.lang.System.clearProperty()用法及代码示例
- Java Java.lang.System.console()用法及代码示例
- Java Java.lang.System.currentTimeMillis()用法及代码示例
- Java Java.lang.System.exit()用法及代码示例
- Java Java.lang.System.gc()用法及代码示例
- Java Java.lang.System.getenv()用法及代码示例
- Java Java.lang.System.getProperties()用法及代码示例
- Java Java.lang.System.getProperty()用法及代码示例
- Java Java.lang.System.getSecurityManager()用法及代码示例
- Java Java.lang.System.identityHashCode()用法及代码示例
- Java Java.lang.System.load()用法及代码示例
- Java Java.lang.System.mapLibraryName()用法及代码示例
- Java Java.lang.System.nanoTime()用法及代码示例
- Java Java.lang.System.runFinalization()用法及代码示例
- Java Java.lang.System.setErr()用法及代码示例
- Java Java.lang.System.setIn()用法及代码示例
- Java Java.lang.System.setOut()用法及代码示例
- Java Java.lang.System.setProperties()用法及代码示例
- Java Java.lang.System.setProperty()用法及代码示例
- Java Java.lang.SecurityManager.checkAccept()用法及代码示例
- Java Java.lang.SecurityManager.checkAccess()用法及代码示例
- Java Java.lang.SecurityManager.checkConnect()用法及代码示例
- Java Java.lang.SecurityManager.checkCreateClassLoader()用法及代码示例
- Java Java.lang.SecurityManager.checkDelete()用法及代码示例
注:本文由纯净天空筛选整理自佚名大神的英文原创作品 Java.lang.System class in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。