Java Java类
System 类提供的设施包括标准输入、标准输出和错误输出流;访问外部定义的属性和环境变量;一种加载文件和库的方法;以及一种用于快速复制数组的一部分的实用方法。它扩展类对象。
领域:
- public static final InputStream in: “标准”输入流。该流已经打开并准备好提供输入数据。通常,此流对应于键盘输入或主机环境或用户指定的另一个输入源。
- public static final PrintStream out: “标准”输出流。此流已经打开并准备好接受输出数据。通常,此流对应于主机环境或用户指定的显示输出或另一个输出目的地。
- public static final PrintStream err: “标准”错误输出流。此流已经打开并准备好接受输出数据。
通常,此流对应于主机环境或用户指定的显示输出或另一个输出目的地。按照惯例,此输出流用于显示错误消息或其他应立即引起用户注意的信息,即使主要输出流(变量 out 的值)已重定向到文件或其他目标通常不会持续监控。
方法:
1. static void arraycopy(Object source, int sourceStart, Object Target, int targetStart, int size):复制一个数组。要复制的数组在 source 中传递,而在 sourceStart 中开始复制的索引将在 sourceStart 中传递。将接收副本的数组在 target 中传递,副本将在 target 内开始的索引在 targetStart 中传递。大小是被复制的元素的数量。
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));
}
}
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"));
}
}
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");
}
}
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());
}
}
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");
}
}
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);
}
}
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 gfg = System.getenv();
Set keySet = gfg.keySet();
for(String key : keySet)
{
System.out.println("key= " + key);
}
// checking specific environment variable
System.out.println(System.getenv("PATH"));
}
}
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
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");
}
}
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
// 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();
}
}
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());
}
}
输出:
[6, 7, 1, 2, 10]
2. static String clearProperty(String key):移除指定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):设置指定key所指示的系统属性。
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.静态控制台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虚拟机的高分辨率时间源的当前值,单位为纳秒。
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. static void exit(int status):终止当前运行的Java虚拟机。该参数用作状态码;按照惯例,非零状态码表示异常终止。
该方法调用 Runtime 类中的 exit 方法。此方法永远不会正常返回。
调用 System.exit(n) 实际上等效于调用:
Runtime.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():运行垃圾收集器。调用 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. static Map getenv():返回当前系统环境的不可修改的字符串映射视图。环境是从名称到值的系统相关映射,从父进程传递到子进程。
如果系统不支持环境变量,则返回一个空映射。
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(String name):获取指定环境变量的值。环境变量是系统相关的外部命名值。
系统属性和环境变量在概念上都是名称和值之间的映射。这两种机制都可用于将用户定义的信息传递给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 gfg = System.getenv();
Set 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.静态属性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
输出:
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. static 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. static void 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):重新分配“标准”错误输出流。
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):重新分配“标准”输入流。
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):重新分配“标准”输出流。
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 inheritChannel():返回从创建此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"