Java System setOut() 方法



描述

Java System setOut() 方法重新分配“标准”输出流。

声明

以下是java.lang.System.setOut() 方法的声明

public static void setOut(PrintStream out)

参数

out − 这是标准输出流。

返回值

此方法不返回任何值。

异常

SecurityException − 如果存在安全管理器并且其 checkPermission 方法不允许重新分配标准输出流。

示例:将输出设置为文件

以下示例演示了 Java System setOut() 方法的用法。在这个程序中,我们创建了一个 FileOutputStream 对象并使用底层文件 file.txt 初始化它。然后使用 setOut() 方法,我们将标准输出设置为该文件,然后打印消息。

package com.tutorialspoint;

import java.io.*;

public class SystemDemo {

   public static void main(String[] args) throws Exception {
    
      // create file
      FileOutputStream f = new FileOutputStream("file.txt");

      System.setOut(new PrintStream(f));

      // this text will get redirected to file
      System.out.println("This is System class!!!");
   }
} 

输出

让我们假设我们有一个文本文件file.txt,它作为我们示例程序的输出生成。该文件包含:

This is System class!!!

示例:将标准流设置为控制台

以下示例演示了 Java System setOut() 方法的用法。在这个程序中,使用 setOut() 方法,我们将标准输出设置为控制台,然后打印消息。

package com.tutorialspoint;

public class SystemDemo {

   public static void main(String[] args) throws Exception {
 
      System.setOut(System.out);
      
      // redirect the output
      System.out.println("This will get redirected to console");
   }
} 

输出

让我们编译并运行上面的程序,这将产生以下结果:

This will get redirected to console
java_lang_system.htm
广告
© . All rights reserved.