How to get output stream name (i.e. stderr or stdout) in java?

In Java, how can I find the name of the stream that is passed as an argument if the given stream is either System.err or System.out ?

 public String getStreamName(OutputStream arg0) { String streamName = ????; return "This is stream: " + streamName; } 

should return something like:

 This is stream: System.err 

I tried arg0.toString() , but this does not seem useful, since the return name is something like java.io.PrintStream@71cb25 and changes every time it starts. If the name was fixed, I could just compare it with the famous names for stdout and stderr.

+4
source share
3 answers

Try the following:

 public void printStreamName(OutputStream stream) { String streamName = "Other"; if(stream instanceof PrintStream) { streamName = stream == System.err ? "System.err" : (stream == System.out ? "System.out" : "Other"); } System.out.println("This is stream: " + streamName); } 
+2
source

System.out and System.err are both instances of PrintStream. Print streams and output streams do not have properties that you could use to differentiate them.

API docs show what is available:

http://docs.oracle.com/javase/6/docs/api/java/io/PrintStream.html

http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html

In this case, you can simply check if this == is either System.out or System.err:

 if (arg0 == System.out) { } else if (arg0 == System.err) { } else { // it is another output stream } 
+3
source

This may not be the best solution, but it works.

 public String getStreamName(OutputStream arg0) { boolean lol = arg0.equals(System.err); String streamName; if(lol) streamName = "System.err"; else streamName = "System.out"; return "This is stream: " + streamName; } 

Edit:

 public String getStreamName(OutputStream arg0) { return "This is stream: " + ((arg0.equals(System.err)) ? "System.err" : "System.out"); } 
+1
source

Source: https://habr.com/ru/post/1447259/


All Articles