For example, in the code, I have: System.out.println("Hello World");
The console will print: Hello World
So, I want to save the console output into a text file. Can anyone please hint me through this?
For example, in the code, I have: System.out.println("Hello World");
The console will print: Hello World
So, I want to save the console output into a text file. Can anyone please hint me through this?
Create a file, and set as the out of the System class.
File file = new File("out.txt"); //Your file
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println("This goes to out.txt");
System class provide you a way to dump output in different stream which is System#setOut(PrintStream out)
Using this method you can pass you FileInputstream to System.setOut
and you can save the console output.
PrintStream printStream = new PrintStream(new FileOutputStream(file));
System.setOut(printStream);
One interesting part of this question is though out
is declared as final in System class but still you reassign this by System#setOut
.