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.