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,286
  • 2
  • 40
  • 80
JDL Wahaha
  • 695
  • 1
  • 14
  • 22

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
  • 31,165
  • 11
  • 75
  • 105
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
  • 40,646
  • 13
  • 77
  • 103