當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.lang.System用法及代碼示例


System 類提供的設施包括標準輸入、標準輸出和錯誤輸出流;訪問外部定義的屬性和環境變量;加載文件和庫的方法;以及一種用於快速複製數組的一部分的實用方法。它擴展了對象類。

領域:

  1. 公共靜態最終InputStream:“standard” 輸入流。該流已打開並準備好提供輸入數據。通常,該流對應於鍵盤輸入或主機環境或用戶指定的另一個輸入源。
  2. 公共靜態最終PrintStream輸出:“standard” 輸出流。該流已打開並準備好接受輸出數據。通常,該流對應於顯示輸出或由主機環境或用戶指定的另一個輸出目的地。
  3. 公共靜態最終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.lang.System class in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。