Core Java

Java System.in System.out System.error Example

1. Introduction

In this post, we feature a comprehensive article on Java System.in System.out System.error. Java has provided java.lang.System class since version 1.0. The System class contains a static System.in for the standard keyboard input, static System.out for the system console output, and static System.err for error output streams to the system console. Here are the definitions:

static InputStream in - the "standard" input stream.
static PrintStream out - the "standard" output stream.
static PrintStream err - the "standard" error output stream.
static void setIn​(InputStream in) - reassigns the "standard" input stream.
static void setOut​(PrintStream out) - reassigns the "standard" output stream.
static void setErr​(PrintStream err) - reassigns the "standard" error output stream.

Java abstract InputStream class models the input streams of bytes. We can use the System.setIn method to change the input stream to any of the following classes:

Java PrintStream class is a subclass from FileOutputStream. We can use the setOut and setErr methods to change the output and error output streams.

In this example, I will demonstrate how to 

  • read inputs from System.in
  • write outputs to System.out
  • write error outputs to System.err
  • re-assign System.in from FileInputStream, URL, and ByteArrayInputStream
  • re-assign System.out to a file
  • re-assign System.err to a file

2. Technologies used

The example code in this article was built and run using:

  • Java 1.11
  • Maven 3.3.9
  • Eclipse Oxygen
  • JUnit 4.12

3. Maven Project

3.1 Dependency

Add JUnit to the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jcg.zheng.demo</groupId>
	<artifactId>java-system-in-out-error-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<release>11</release>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
</project>

3.2 InputStreamHelper

In this step, I will create three methods to change System.in to use ByteArrayInputStream, FileInputStream, and URL.

  • setIn_from_ByteArrayInputStream(String msg) – Creates a ByteArrayInputStream from the given string message and reset System.in with it.
  • setIn_from_FileInputStream(String fileName) – Creates a FileInputStream from the given file name and reset System.in with it.
  • setIn_from_URL(String url) – Creates an InputStream from the given url and reset System.in with it.

InputStreamHelper .java

package jcg.zheng.demo;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class InputStreamHelper {

	public static void setIn_from_ByteArrayInputStream(String msg) {
		ByteArrayInputStream binput = new ByteArrayInputStream(msg.getBytes());
		System.setIn(binput);
	}

	public static void setIn_from_FileInputStream(String fileName) throws FileNotFoundException {
		FileInputStream in_file = new FileInputStream(fileName);
		System.setIn(in_file);
	}

	public static void setIn_from_URL(String url) throws MalformedURLException, IOException {
		InputStream in_file = new URL(url).openStream();
		System.setIn(in_file);
	}

}

3.3 PrintStreamHelper

In this step, I will create three methods to change the System.out and System.err to use FileOutputStream.

PrintStreamHelper.java

package jcg.zheng.demo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class PrintStreamHelper {

	public static void setError_from_File(String filename) throws FileNotFoundException {
		PrintStream error_file = new PrintStream(filename);
		System.setErr(error_file);
	}

	public static void setOut_from_File(String filename) throws FileNotFoundException {
		PrintStream out_file = new PrintStream(filename);
		System.setOut(out_file);
	}

	public static void setOut_from_OutStream(String filename) throws FileNotFoundException {
		PrintStream output = new PrintStream(new FileOutputStream(filename));
		System.setOut(output);
	}
}

3.4 ScannerApp

In this step, I will create a ScannerApp class to read inputs from System.in, write data to System.out, and write the exception message to System.err.

ScannerApp.java

package jcg.zheng.demo;

import java.util.Scanner;

public class ScannerApp {

	public static void main(String[] argu) {
		ScannerApp sapp = new ScannerApp();
		System.out.println("Enter anything from the keyboard:");
		sapp.scan_in_write_out_and_log_error();
	}

	public String scan_in_write_out_and_log_error() {
		String ret = null;

		try (Scanner sc = new Scanner(System.in)) {
			while (sc.hasNextLine()) {
				String valueEntered = sc.nextLine();
				ret = valueEntered;
				System.out.println("Value from System.in:" + ret);
				if ("q".equalsIgnoreCase(valueEntered)) {
					System.out.println("Bye!");
					System.exit(0);
				}

				try {
					Integer.parseInt(valueEntered);
				} catch (NumberFormatException e) {
					System.err.println("Caught NumberFormatException " + e.getMessage());

				}
			}
		}
		return ret;
	}
}

Execute it as a Java application and capture the output.

Output

Enter anything from the keyboard:
a
Value from System.in:a
Caught NumberFormatException For input string: "a"
12
Value from System.in:12
q
Value from System.in:q
Bye!

3.5 InputStreamReaderApp

In this step, I will create an InputStreamReaderApp class to read inputs from System.in, write data to System.out, and write the exception message to System.err.

InputStreamReaderApp.java

package jcg.zheng.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class InputStreamReaderApp {
	public static void main(String[] argu) {
		InputStreamReaderApp iApp = new InputStreamReaderApp();		
		System.out.println("Enter anything from the keyboard (q- quit):");		 
		iApp.read_in_write_out_and_log_error();
		
	}

	public String read_in_write_out_and_log_error() {
		String ret = null;
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
			String strCurrentLine = null;

			while ((strCurrentLine = br.readLine()) != null) {
				System.out.println(strCurrentLine);
				if ("q".equalsIgnoreCase(strCurrentLine)) {
					System.out.println("Bye!");
					ret = "Bye";
					System.exit(0);
				} else {
					System.out.println("Value from System.in:" + strCurrentLine);
					try {
						ret = String.format("%4d", Integer.parseInt(strCurrentLine));
					} catch (NumberFormatException e) {
						ret = "Error";
						System.err.println("Caught NumberFormatException " + e.getMessage());
					}
				}
			}

		} catch (IOException e) {
			System.err.println("Caught Exception " + e.getMessage());
			ret = "Error";
		}
		return ret;
	}
}

Execute it as a Java application and capture the output.

Output

Enter anything from the keyboard (q- quit):
this will throw exception as it is not a number
this will throw exception as it is not a number
Value from System.in:this will throw exception as it is not a number
Caught NumberFormatException For input string: "this will throw exception as it is not a number"
12
12
Value from System.in:12
34
34
Value from System.in:34
q
q
Bye!

4. JUnit Tests

I will create two JUnit classes to demonstrate how to read data from System.in, write the outputs to System.out, and write the error outputs to System.err.

4.1 ScannerAppTest

In this step, I will create four test methods:

  • test_url_as_in – resets System.in from a URL
  • test_bytearray_as_in – resets System.in from a ByteArrayInputStream
  • test_file_as_in_out – re-assigns a file to System.in and System.out
  • test_file_as_in_out_error – re-assigns a file to System.in, System.out , and System.err

ScannerAppTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.FileNotFoundException;

import org.junit.Test;

public class ScannerAppTest {

	ScannerApp scannerApp = new ScannerApp();

	@Test
	public void test_bytearray_as_in() {
		InputStreamHelper.setIn_from_ByteArrayInputStream("hello");
		String demo = scannerApp.scan_in_write_out_and_log_error();
		assertEquals("hello", demo);
	}


	@Test
	public void test_file_as_in_out() {
		try {
			PrintStreamHelper.setOut_from_OutStream("data/error_file.log");
			InputStreamHelper.setIn_from_FileInputStream("data/scan_in_file.txt");
			String entered = scannerApp.scan_in_write_out_and_log_error();
			assertNotNull(entered);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test_file_as_in_out_error() {
		try {
			InputStreamHelper.setIn_from_FileInputStream("data/scan_in_file.txt");
			PrintStreamHelper.setError_from_File("data/error_file.log");
			PrintStreamHelper.setOut_from_File("data/out_file.txt");

			String demo = scannerApp.scan_in_write_out_and_log_error();
			assertEquals("qest", demo);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	@Test
	public void test_url_as_in() {
		try {
			InputStreamHelper.setIn_from_URL("https://gmail.com");
			String lastStr = scannerApp.scan_in_write_out_and_log_error();
			assertNotNull(lastStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Execute mvn test -Dtest=ScannerAppTest and capture the output.

Output

C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo>mvn test -Dtest=ScannerAppTest
[INFO] Scanning for projects...
[INFO]
[INFO] ------------< jcg.zheng.demo:java-system-in-out-error-demo >------------
[INFO] Building java-system-in-out-error-demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-system-in-out-error-demo ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-system-in-out-error-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 6 source files to C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-system-in-out-error-demo ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-system-in-out-error-demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-system-in-out-error-demo ---
[INFO] Surefire report directory: C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.ScannerAppTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.101 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  15.014 s
[INFO] Finished at: 2019-07-14T20:41:48-05:00
[INFO] ------------------------------------------------------------------------

4.2 InputStreamReaderAppTest

In this step, I will create two test methods:

  • test_file_as_in – resets System.in from a file
  • test_file_as_in_out – resets System.in and System.out from files

InputStreamReaderAppTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import java.io.FileNotFoundException;

import org.junit.Test;

public class InputStreamReaderAppTest {

	InputStreamReaderApp inputStreamReaderApp = new InputStreamReaderApp();

	@Test
	public void test_file_as_in() {
		try {
			InputStreamHelper.setIn_from_FileInputStream("data/in_file.txt");
			String data = inputStreamReaderApp.read_in_write_out_and_log_error();
			assertEquals(" 345", data);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void test_file_as_in_out() {
		try {
			InputStreamHelper.setIn_from_FileInputStream("data/in_file.txt");
			PrintStreamHelper.setOut_from_OutStream("data/testFile.bin");
			String data = inputStreamReaderApp.read_in_write_out_and_log_error();
			assertEquals(" 345", data);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}

Execute mvn test -Dtest=InputStreamReaderAppTest and capture the output.

Output

C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo>mvn test -Dtest=InputStreamReaderAppTest
[INFO] Scanning for projects...
[INFO]
[INFO] ------------< jcg.zheng.demo:java-system-in-out-error-demo >------------
[INFO] Building java-system-in-out-error-demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ java-system-in-out-error-demo ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\src\main\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ java-system-in-out-error-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 6 source files to C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ java-system-in-out-error-demo ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ java-system-in-out-error-demo ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent!
[INFO] Compiling 2 source files to C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ java-system-in-out-error-demo ---
[INFO] Surefire report directory: C:\MaryZheng\Workspaces\jdk12\java-system-in-out-error-demo\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.InputStreamReaderAppTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.182 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  11.763 s
[INFO] Finished at: 2019-07-14T20:39:30-05:00
[INFO] ------------------------------------------------------------------------

5. Eclipse System Setting

As you can see, Java System class provides setIn, setOut, and setErr to use other InputStream and PrintStream. Eclipse IDE provides a convenient UI to redirect them. I will demonstrate with the ScannerApp class created at step 3.4.

Right click on ScannerApp, select Run As ->Run Configuration.

Click on the Common tab, enter the Output File as “SystemOutFile.txt”.

Java System.in System.out System.error - Eclipse Common Setting
Figure 1 Eclipse Common Setting for Standard Input and Output

Click the Apply button and then click the "Run" button.

Capture the Eclipse console output.

Eclipse Console

[Console output redirected to file:C:\MaryZheng\DevTools\Eclipse\eclipse64\4.11\eclipse\SystemOutFile.txt]
Enter anything from the keyboard:
test
Value from System.in:test
Caught NumberFormatException For input string: "test"
12
Value from System.in:12
q
Value from System.in:q
Bye!

View the output file content.

SystemOutFile.txt

Enter anything from the keyboard:
Value from System.in:test
Caught NumberFormatException For input string: "test"
Value from System.in:12
Value from System.in:q
Bye!

6. Java System.in System.out System.err – Summary

In this example, I demonstrated how to read the data from System.in, write the outputs to System.out, and write the error outputs to System.err. I also demonstrated how to reassign System.in to different InputStream classes and reassign System.out to a different PrintStream.

7. Download the Source Code

This example consists of a Maven project which deals with System.in, System.out, and System.err.

Download
You can download the full source code of this example here: Java System.in System.out System.error Example

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button