JAVAJava中的lang.System类

系统类提供的功能包括标准输入、标准输出和错误输出流;访问外部定义的属性和环境变量;加载文件和库的方法;以及用于快速复制阵列的一部分的实用方法。它扩展了类对象。

null

领域:

  1. 公共静态最终输入流输入: “标准”输入流。该流已经打开,可以提供输入数据。通常,该流对应于键盘输入或主机环境或用户指定的另一个输入源。
  2. 公共静态最终打印流输出: “标准”输出流。此流已打开,可以接受输出数据。通常,该流对应于主机环境或用户指定的显示输出或另一个输出目标。
  3. 公共静态最终打印流错误: “标准”错误输出流。此流已打开,可以接受输出数据。 通常,该流对应于主机环境或用户指定的显示输出或另一个输出目标。按照惯例,该输出流用于显示错误消息或其他信息,即使主输出流(变量out的值)已被重定向到通常不被持续监视的文件或其他目的地,用户也应立即注意到这些信息。

方法:

1.静态void arraycopy(对象源、int-sourceStart、对象目标、int-targetStart、int-size): 复制一个数组。要复制的数组在source中传递,复制将在source中开始的索引在sourceStart中传递。将接收副本的数组传入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.静态字符串clearProperty(字符串键): 删除指定键指示的系统属性。

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.静态字符串getProperty(字符串键): 获取由指定键指示的系统属性。

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.静态字符串getProperty(字符串键、字符串定义): 获取由指定键指示的系统属性。

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.静态字符串setProperty(字符串键、字符串值): 设置由指定键指示的系统属性。

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/abhishekvermanullUSnone of your business

6.静态控制台(): 返回与当前Java虚拟机关联的唯一控制台对象(如果有)。

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.静态长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.静态长时间() 返回正在运行的Java虚拟机的高分辨率时间源的当前值(以纳秒为单位)。

Syntax: public static long nanoTime()Returns: the current value of the running Java Virtual Machine's high-resolution time source, in nanosecondsException: 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: 1499520649545current time in nano sec: 29976939759226

9.静态无效退出(int状态): 终止当前运行的Java虚拟机。该参数充当状态代码;按照惯例,非零状态代码表示异常终止。 此方法在类运行时调用exit方法。这个方法永远不会正常返回。 呼叫系统。退出(n)实际上相当于呼叫: 运行时。getRuntime()。出口(n)

Syntax: public static void exit(int status)Returns: NAException: 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.静态无效gc(): 运行垃圾收集器。调用gc方法意味着Java虚拟机将精力扩展到回收未使用的对象,以便使它们当前占用的内存可用于快速重用。当控件从方法调用返回时,Java虚拟机已尽最大努力从所有丢弃的对象中回收空间。

Syntax: public static void gc()Returns: NAException: 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: 128974848Initial free memory: 126929976Free memory after garbage collection: 128632160Free memory after allocation: 127950520Memory used by allocation: 681640Free memory after  collecting discarded Integers: 128643472

11.静态映射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.静态字符串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 nullSecurityException - 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_5396key= PATHkey= J2D_PIXMAPSkey= SHELLkey= USERkey= TMPDIRkey= SSH_AUTH_SOCKkey= XPC_FLAGSkey= LD_LIBRARY_PATHkey= __CF_USER_TEXT_ENCODINGkey= Apple_PubSub_Socket_Renderkey= LOGNAMEkey= LC_CTYPEkey= XPC_SERVICE_NAMEkey= PWDkey= JAVA_MAIN_CLASS_2336key= SHLVLkey= HOMEkey= _/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<Object> keySet = gfg.keySet();
for (Object key : keySet)
{
System.out.println( "key= " + key);
}
}
}


输出:

key= java.runtime.namekey= sun.boot.library.pathkey= java.vm.versionkey= user.country.formatkey= gopherProxySetkey= java.vm.vendorkey= java.vendor.urlkey= path.separatorkey= java.vm.namekey= file.encoding.pkgkey= user.countrykey= sun.java.launcherkey= sun.os.patch.levelkey= java.vm.specification.namekey= user.dirkey= java.runtime.versionkey= java.awt.graphicsenvkey= java.endorsed.dirskey= os.archkey= java.io.tmpdirkey= line.separatorkey= java.vm.specification.vendorkey= os.namekey= sun.jnu.encodingkey= java.library.pathkey= java.specification.namekey= java.class.versionkey= sun.management.compilerkey= os.versionkey= http.nonProxyHostskey= user.homekey= user.timezonekey= java.awt.printerjobkey= file.encodingkey= java.specification.versionkey= java.class.pathkey= user.namekey= java.vm.specification.versionkey= sun.java.commandkey= java.homekey= sun.arch.data.modelkey= user.languagekey= java.specification.vendorkey= awt.toolkitkey= java.vm.infokey= java.versionkey= java.ext.dirskey= sun.boot.class.pathkey= java.vendorkey= file.separatorkey= java.vendor.url.bugkey= sun.io.unicode.encodingkey= sun.cpu.endiankey= socksNonProxyHostskey= ftp.nonProxyHostskey= sun.cpu.isalist

14.静态安全管理器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.静态无效集合安全管理器(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.静态无效设置错误(打印流错误): 重新分配“标准”错误输出流。

Syntax: public static void setErr(PrintStream err)Returns: NAException: SecurityException - if a security manager exists and its checkPermission method doesn't allow reassigning of the standard error output stream.

17.静态无效设置(输入流输入): 重新分配“标准”输入流。

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.静态无效放样(打印流输出): 重新分配“标准”输出流。

Syntax: public void setOut(PrintStream out)Returns: NAException: 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" .getBytes());
// set error stream
System.setErr( new PrintStream(OUT));
System.err.write( "Exception message" .getBytes());
}
}


输出: 上述java代码的输出取决于“input.txt”文件中的内容。 创建自己的“input.txt”,然后运行代码并检查输出。

19.静态无效加载(字符串文件名): 从本地文件系统以动态库的形式加载具有指定文件名的代码文件。filename参数必须是完整的路径名。

Syntax: public static void load(String filename)Returns: NAException: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic libraryUnsatisfiedLinkError - if the file does not exist.NullPointerException - if filename is null

20.静态void loadLibrary(字符串libname): 加载libname参数指定的系统库。库名称映射到实际系统库的方式取决于系统。

Syntax: public static void loadLibrary(String libname)Returns: NAException: SecurityException - if a security manager exists and its checkLink method doesn't allow loading of the specified dynamic libraryUnsatisfiedLinkError - if the library does not exist.NullPointerException - if libname is null

21.静态字符串mapLibraryName(字符串libname): 将库名称映射为表示本机库的特定于平台的字符串。

Syntax: public static String mapLibraryName(String libname)Returns: a platform-dependent native library name.Exception: NullPointerException - if libname is null

22.静态void runFinalization(): 运行任何待终结对象的终结方法。调用此方法意味着Java虚拟机将精力扩展到运行已发现被丢弃但其finalize方法尚未运行的对象的finalize方法。当控件从方法调用返回时,Java虚拟机已尽最大努力完成所有未完成的终结。

Syntax: public static void runFinalization()Returns: NAException: 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.静态int-identityHashCode(对象x): 无论给定对象的类是否重写hashCode(),为给定对象返回与默认方法hashCode()相同的哈希代码。空引用的哈希代码为零。

Syntax: public static int identityHashCode(Object x)Returns: the hashCode.Exception: NA.

24.静态通道inheritedChannel(): 返回从创建此Java虚拟机的实体继承的通道。

Syntax: public static Channel inheritedChannel().Returns:  inherited channel, if any, otherwise null.Exception: IOException - If an I/O error occursSecurityException - If a security manager is present and it does not permit access to the channel.

25.静态字符串lineSeparator(): 返回系统相关的行分隔符字符串。它始终返回相同的值–系统建筑红线分隔符的初始值。

Syntax: public static String lineSeparator()Returns: On UNIX systems, it returns ""; on Microsoft Windows systems it returns "
".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());
}
}


输出:

1735600054null"
"

本文由 阿布舍克·维马 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享