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
Stream
Field
Default Destination
Standard input
System.in
Keyboard (console input)
Standard output
System.out
Console
Standard error
System.err
Console (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 Case
Description
Testing
Simulate user input or capture console output
Logging
Redirect System.out / System.err to a log file
GUI apps
Capture console output into a GUI text area
Scripting tools
Connect 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.