How to Redirect Standard Output/Error in Java

System.out and System.err stream objects are mapped to “standard” output and error stream respectively. By default, Java display standard output/error on display console. Thus, when we print a statement using System.out:

System.out.println("Hello World!"); System.err.println("errr.. Hello World!");
Code language: Java (java)

It prints the messages to default console. What if you want to reassign the “standard” output and error stream? Lets say you want to redirect all those standard out messages in a File. System class provides some useful API to re-assign “standard” input, output and error streams.

  • setErr(PrintStream err): Reassigns the “standard” error output stream
  • setIn(InputStream in): Reassigns the “standard” input stream.
  • setOut(PrintStream out): Reassigns the “standard” output stream.

In below Java code we reassign “standard” output to a file and redirect all sysout messages to that file.

System.out.println("January"); System.out.println("February"); PrintStream ps = new PrintStream("C:/sample.txt"); System.setOut(ps); System.out.println("March"); System.out.println("April"); ps.close();
Code language: Java (java)

Output:

January February

File: sample.txt

March April

Thus only January and February will be displayed in console and March April will be printed in sample.txt file.

View Comments

  • If you want to bring console output back you can use this code:
    [code language="java"]
    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
    PrintStream defaultPrintStream = new PrintStream(new BufferedOutputStream(fdOut, 128), true);
    System.setOut(defaultPrintStream)
    [/code]
    I took it right from initializeSystemClass() method of System class.

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

5 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

5 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

5 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

5 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

5 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago