Java.Streams.Is it possible to redirect standard input/output streams?

Java allows you to redirect standard input, output, and error streams quite easily using the System class. It’s super useful for logging, testing, piping data between tools, and even simulating a console in GUI apps.

🔁 Standard I/O Streams in Java

StreamFieldDefault Destination
Standard inputSystem.inKeyboard (console input)
Standard outputSystem.outConsole
Standard errorSystem.errConsole (often red-colored)

🔧 How to Redirect Them

🔹 1. Redirect System.out and System.err

PrintStream fileOut = new PrintStream("output.txt");
System.setOut(fileOut);     // Now System.out goes to the file
System.setErr(fileOut);     // So does System.err

System.out.println("This goes to output.txt");
System.err.println("So does this error message");

🔹 2. Redirect System.in

String simulatedInput = "42\nhello\n";
InputStream fakeInput = new ByteArrayInputStream(simulatedInput.getBytes());
System.setIn(fakeInput);

Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();     // Reads 42
String word = scanner.next();       // Reads "hello"

System.out.println("Read: " + number + " and " + word);

💡 Real-World Use Cases

Use CaseDescription
TestingSimulate user input or capture console output
LoggingRedirect System.out / System.err to a log file
GUI appsCapture console output into a GUI text area
Scripting toolsConnect Java with other command-line tools (like in a shell)

⚠️ Caveats

  • Redirection affects the entire JVM, so be cautious in multi-threaded apps.
  • Always restore original streams if you’re redirecting temporarily.
PrintStream originalOut = System.out;
// ... redirect ...
System.setOut(originalOut); // Restore

🧵 TL;DR

OperationCode
Redirect stdoutSystem.setOut(new PrintStream("file.txt"))
Redirect stderrSystem.setErr(new PrintStream("errors.log"))
Redirect stdinSystem.setIn(new ByteArrayInputStream("input".getBytes()))
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.