重定向java中jar文件的stdout



场景如下-我有一个主java文件file1和一个名为Minimizejar文件。我创建了一个classobject,称为MinimizeTable,它在jar中定义。现在,这个对象的创建导致一些行被打印到jar中定义的stdout。我只想重定向这个输出。除此之外,我的主文件还有许多stdout行,这些行必须打印到stdout本身。是否只重定向jar文件打印的内容,而不重定向其余内容?我在下面定义了情况-

class file1{
   public static void main(String[] args)
   {
      MinimizedTable M = new MinimizedTable(); //this instantly prints stuff out which I want to be redirected and not printed to stdout.
      System.out.println("Hello"); //This line must be printed to stdout. 
   }
  }

有没有什么方法可以在不接触jar文件的情况下做到这一点?希望我的解释有道理。

没有任何外部依赖,对main进行了轻微修改:

    System.setOut(new FilteredOutput(System.out));
    MinimizedTable M = new MinimizedTable();
    System.out.println("Hello");

然后过滤输出类似这样的东西:

import java.io.OutputStream;
import java.io.PrintStream;

public class FilteredOutput extends PrintStream {
    public FilteredOutput(OutputStream out) {
        super(out);
    }
    @Override
    public void println(String x) {
        if (Thread.currentThread().getStackTrace()[2].getClassName().equals(MinimizedTable.class.getName())) {
            super.println("From MinimizedTable: "+x);
        } else {
        super.println(x);
        }
    }
    ...
}

您可以使用Log4j来实现它,类似于。。。

 log4j.logger.abc.xyz.MinimizedTable=OFF

对于纯java解决方案,请参考这个SO问题。

我来这里是为了搜索重定向stdout。来自的响应BCartolo让我走上了正轨,但只覆盖了println。Bozhao的一篇帖子巧妙地建议写入ByteArrayOutputStream,但没有提供为换行刷新输出的功能。更通用的方法是覆盖底层OutputStream中的写(字节)。

我的应用程序需要将System.out文本发送到"show"方法。重定向命令是

    System.setOut(new PrintStream(new ShowStream()));

其中ShowStream是

/** Text written to a ShowStream is passed to the show method 
 * when a newline is encountered or a flush occurs.
 * CR characters are ignored.
 */
public static class ShowStream extends OutputStream {
    ByteArrayOutputStream buf = new ByteArrayOutputStream(200);
    public ShowStream() {}
    @Override
    public void     close() { flush(); }
    /** show() the buffer contents, if any */
    @Override
    public void     flush() {
        String s = buf.toString();
        buf.reset();
        show(s, bluePainter);
    }
    /** Put characters in a buffer until newline arrives; 
     * then show() the whole
     * @param b Incoming character
     */
    @Override
    public void write(int b) {
        if (b != 'r')   // ignore CR
            buf.write(b);
        if (b == 'n')   // flush after newline
            flush();
    }
}

完整的源代码是Message.java

最新更新