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

笑着哭i 提交于 2019-12-23 15:51:25

问题


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.


回答1:


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);
}



回答2:


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
}



回答3:


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");
}


来源:https://stackoverflow.com/questions/13476375/how-to-get-name-of-output-stream-i-e-stderr-or-stdout-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!