Reputation: 598
I want to save the stdout into a file. For this, I used
System.setOut(new PrintStream(new File("output-file.txt")));
Now, there is no output in the console.
try {
System.setOut(new PrintStream(new File("output-file.txt")));
} catch (Exception e) {
e.printStackTrace();
}
Is there any possibility to show the stdout in the console, although I use stdout to fill a file?
Upvotes: 2
Views: 1711
Reputation: 1
You can make a new subclass of the PrintStream class and then override it's methods to write to a second Stream and then pass that to System.out as you've already one. Further reading & example implementation: https://books.google.ch/books?id=lbnjAwAAQBAJ&lpg=PA326&ots=j7OUeuXzIa&dq=java%20duplicate%20printstream&pg=PA326#v=onepage&q=java%20duplicate%20printstream&f=false
Upvotes: 0
Reputation: 3412
You could create a PrintWriter
with an OutputStream
that does both writes.
final OutputStream stdOut = System.out;
try {
System.setOut(new PrintStream(new OutputStream() {
private PrintStream ps = new PrintStream(new File("output-file.txt"));
@Override
public void write(int b) throws IOException {
ps.write(b);
stdOut.write(b);
}
@Override
public void flush() throws IOException {
super.flush();
ps.flush();
stdOut.flush();
}
@Override
public void close() throws IOException {
super.close();
ps.close();
// stdOut.close(); // Normally not done
}
}));
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Hello, world!");
Upvotes: 3
Reputation: 778
I never tried it, but i guess if you subclass the default Printstream you are able to print to console and file by yourself.
Something like:
class MyPrintStream extends printStream {
private PrintStream secondPrinter;
.....
@Override
public void println(Object content) {
super.println(content);
secondPrinter.println(content);
}
}
and maybe call it like this:
System.out = new MyPrintStream(myFile, System.out);
Upvotes: 1
Reputation: 2601
You can not use the systems OutputStream
to write to 2 sources. It is a static variable and it can only have 1 value at a time.
You can try however, saving a reference to the consoles default OutputStream
, and then changing the Systems OutputStream
to your custom output stream, and write to both of them with a custom method.
Upvotes: 0