4

I recently recognized that you're able to close the PrintStream System.out!

So the code snippet:

System.out.println("foo");
System.out.close();
System.out.println("bar");

will produce the output:

foo

instead of:

foo
bar

Now to my question:

Is there a way to restore the PrintStream after closing it?

I've seen there's a setOut(PrintStream p) method in System which allows me to set the System.out stream to some other stream. But i don't know how to create a stream that's printing to console!


Once again, my question is NOT if i can reopen the System.out printstream! I'm asking if one could reproduce the steps that java is doing internally to open a PrintStream that is printing to the console AFTER the System.out PrintStream was closed!

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
  • 2
    A closed stream cannot perform output operations and cannot be reopened – Abdelhak Dec 15 '15 at 09:56
  • Well i might have written this question badly. I'm aware that a closed stream is closed forever but i'd like to know if I can restore it to default somehow (e.g. there's a `setOut()` method which allows me to set a PrintStream as System.out, but i don't know how to create a Printstream that prints to console!) – ParkerHalo Dec 15 '15 at 09:58
  • @ParkerHalo I tried to recreate what System class does internally - `FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);System.setOut(new PrintStream(new BufferedOutputStream(fdOut, 128), true));` but it didn't work. Maybe I missed something. – Eran Dec 15 '15 at 10:31
  • @Eran that's some nice idea! I'll try to play around with that a bit! – ParkerHalo Dec 15 '15 at 10:33
  • @Eran problem seems to be that `System.out.close()` somehow changes something at the `FileDescriptor.out`... Before the close, the `FileDescriptor.out` is valid and afterwards it's not... – ParkerHalo Dec 15 '15 at 10:37
  • @ParkerHalo Try to create a new descripor - `FileDescriptor desc = new FileDescriptor(); desc.handle = set(1);` – Eran Dec 15 '15 at 10:39
  • hmmm... the handle is private and FileDescriptor cannot be subclassed... – ParkerHalo Dec 15 '15 at 10:46
  • @Eran agreed! But thanks for trying ;)! – ParkerHalo Dec 15 '15 at 11:15
  • here a nice explanation http://stackoverflow.com/questions/8941298/system-out-closed-can-i-reopen-it – SüniÚr Dec 16 '15 at 08:28
  • @Csanesz i know i could just NOT close the stream... I'm very aware of that... My question is if there's any way to reopen it by myself. But we're stuck at some point there becaue the handle of FileDescriptor is private and cannot be changed! – ParkerHalo Dec 16 '15 at 08:31
  • What if you just disable `close` for `System.out` and `System.err`? – Lyubomyr Shaydariv Dec 17 '15 at 20:37

0 Answers0