In Java, how can I find the name of the stream which is passed as an argument, provided 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've tried arg0.toString()
, but that doesn't seem useful, as the name returned is something like java.io.PrintStream@71cb25
and changes with each run. If the name was fixed, I could just compare it with the known names for stdout and stderr.
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.
The 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 just check if it is == to either System.out or System.err:
if (arg0 == System.out) {
} else if (arg0 == System.err) {
} else {
// it is another output stream
}
Try this:
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);
}
Maybe not 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");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.