Java System setIn() 方法



描述

Java System setIn() 方法重新分配“標準”輸入流。

宣告

以下是 java.lang.System.setIn() 方法的宣告

public static void setIn(InputStream in)

引數

in − 這是新的標準輸入流。

返回值

此方法不返回值。

異常

SecurityException − 如果存在安全管理器並且其 checkPermission 方法不允許重新分配標準輸入流。

示例:從檔案讀取

以下示例演示了 Java System setIn() 方法的用法。在此程式中,我們使用 setIn() 方法將 FileInputStream 設定為輸入。現在使用 System.in.read(),從檔案中讀取第一個字元並將其顯示在控制檯上。

package com.tutorialspoint;

import java.io.FileInputStream;

public class SystemDemo {

   public static void main(String[] args) throws Exception {
    
      // existing file
      System.setIn(new FileInputStream("file.txt"));

      // read the first character in the file
      char ret = (char)System.in.read();

      // returns the first character
      System.out.println(ret);              
   }
} 

輸出

假設我們有一個文字檔案 file.txt,其中包含:

This is System class!!!

編譯將產生以下結果:

T

示例:從控制檯讀取

以下示例演示了 Java System setIn() 方法的用法。在此程式中,我們使用 setIn() 方法將 System.in 設定為輸入。現在使用 System.in.read(),從控制檯中讀取第一個字元並將其顯示在控制檯上。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) throws Exception {
    
      // existing file
      System.setIn(System.in);

      // read the first character from the console
      char ret = (char)System.in.read();

      // returns the first character
      System.out.println(ret);              
   }
} 

輸出

編譯將產生以下結果:

T
T
java_lang_system.htm
廣告

© . All rights reserved.