0

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?

Not a bug
  • 4,256
  • 1
  • 38
  • 72
JDL Wahaha
  • 633
  • 1
  • 14
  • 20

2 Answers2

6

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");
Abimaran Kugathasan
  • 29,154
  • 11
  • 70
  • 102
3

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.

Subhrajyoti Majumder
  • 39,719
  • 12
  • 74
  • 101