Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listener to prevent System.out display on the screen

Tags:

java

I was doing my academic project and while building and testing i have put many println() statements.

But when I had to submit all prints should not be displayed.

Can i implement something like listener which will be invoked when System.out is tried to be executed and prevents it from displaying. I dont know how feasible this idea is but just want to know whether its possible or not. I know i could have used a log file or write into a file but again its just a thought came into my mind if I have to disable SOP how can i do it ..

thanks

like image 589
harshit Avatar asked Dec 02 '22 05:12

harshit


2 Answers

use System.setOut function (and setErr) The following program will only print 1: (and not 2)

public static void main(String[] args) throws FileNotFoundException {
    System.out.println("1");
    System.setOut(new PrintStream(new OutputStream() {
        @Override
        public void write(int arg0) throws IOException {
            // TODO Auto-generated method stub

        }
    }));
    System.out.println("2");
}
like image 122
ekeren Avatar answered Dec 06 '22 10:12

ekeren


The correct thing to do is to either use flags before printlns, or better yet, to use a Logger (there are many versions available).

It is, however, possible to reroute all System.out away. Search for "redirect system.out" and you will find plenty of examples.

like image 31
Uri Avatar answered Dec 06 '22 11:12

Uri