java中的system.out.println重定向

我想捕获println并重定向到文件并打印它

这是我的代码,我希望打印123 / n 456

但这不起作用,我认为在打印outContent之前我需要一些东西来阻止捕获,但我不知道该怎么做。

public static void main(String args[]){ ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); System.out.println("123"); System.out.println("456"); System.out.println(outContent.toString()); } 

回到当天,在我开始使用log4j或其他专用记录器之前,我使用的技术类似于下面的技术。

本质上,它是一个代理PrintStream ,它将内容回送到原始PrintStream ,并将内容写入其他OutputStream (例如文件)。

您还可以通过在设置为true时不使用old.write(b)old.write(b)将回显到控制台的标志。 这是一种我用来阻止应用程序向stdout喷出大量垃圾的技术,它可以减慢应用程序的速度,尤其是当你在图形环境中运行时……

 import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; public class RedirectStdOut { public static void main(String[] args) { OutputStream os = null; try { os = new FileOutputStream(new File("Log.txt")); LoggingPrintStream lps = new LoggingPrintStream(os); System.out.println("This is going to the console only..."); lps.install(); System.out.println("This is going to console and file"); System.out.println("Fun times"); lps.uinstall(); System.out.println("This is going to console only..."); } catch (IOException exp) { exp.printStackTrace(); } finally { try { os.close(); } catch (Exception e) { } } } public static class LoggingPrintStream { private OutputStream os; private PrintStream old; public LoggingPrintStream(OutputStream os) { this.os = os; } public void install() { old = System.out; System.setOut(new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { old.write(b); os.write(b); } })); } public void uinstall() throws IOException { try { os.flush(); } finally { try { os.close(); } catch (Exception e) { } System.setOut(old); } } } } 

我试图弄清楚我是否可以将溪流连接起来,但是今天(周五下午)我的头脑无法完成任务。

您应该将out流重定向到这样的文件:

  System.setOut(new PrintStream(new File("")); 

这将在日志文件中重定向所有system.out 。 希望这可以帮助。

将System.out.println重定向到Log4J,同时保留类名信息

以上post在一定程度上解释了如何做到这一点。