如何在 Java 中获取输出流的名称(即 stderr 或 stdout)? [英] How to get name of output stream (i.e, stderr, or stdout) in java?

查看:82
本文介绍了如何在 Java 中获取输出流的名称(即 stderr 或 stdout)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,如果给定的流是 System.errSystem.out,我如何找到作为参数传递的流的名称?

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

应该返回如下内容:

This is stream: System.err

我试过 arg0.toString(),但这似乎没什么用,因为返回的名称类似于 java.io.PrintStream@71cb25 和每次运行都会发生变化.如果名称是固定的,我可以将其与 stdout 和 stderr 的已知名称进行比较.

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.

推荐答案

试试这个:

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

这篇关于如何在 Java 中获取输出流的名称(即 stderr 或 stdout)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆