System.out 到 java 中的文件 [英] System.out to a file in java

查看:25
本文介绍了System.out 到 java 中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从另一个应用程序内部运行一个应用程序以进行测试.我想将被测试应用的输出重定向到一个文件,这样我就可以在每次测试后都有一个日志.

I'm running an application from inside another one for testing purposes. I want to redirect the output for the tested app to a file, so I can have a log after each test.

有没有办法将应用程序的输出从 java 中的命令行重定向到文件?

Is there a way to redirect the output of an app to a file from the command line in java?

推荐答案

您可以使用 Windows 命令行支持的输出流重定向器,*nix shells ,例如

You can use the output stream redirector that is supported by the Windows command line, *nix shells , e.g.

java -jar myjar.jar > output.txt

或者,当您从 vm 内部运行应用程序时,您可以从 java 本身内部重定向 System.out.您可以使用该方法

Alternatively, as you are running the app from inside the vm, you could redirect System.out from within java itself. You can use the method

System.setOut(PrintStream ps)

它替换了标准输出流,因此所有对 System.out 的后续调用都转到您指定的流.您可以在运行包装的应用程序之前执行此操作,例如调用 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));

Which replaces the standard output stream, so all subsequent calls to System.out go to the stream you specify. You could do this before running your wrapped application, e.g. calling System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));

如果您使用的是无法修改的包装器,请创建您自己的包装器.所以你有 FEST 包装器 -> 流重定向器包装器 -> 测试应用程序.

If you are using a wrapper that you can't modify, then create your own wrapper. So you have FEST wrapper -> stream redirector wrapper -> tested app.

例如,您可以像这样实现一个简单的包装器:

For example, you can implement a simple wrapper like this:

public class OutputRedirector
{
   /* args[0] - class to launch, args[1]/args[2] file to direct System.out/System.err to */
   public static void main(String[] args) throws Exception
   {  // error checking omitted for brevity
      System.setOut(outputFile(args(1));
      System.setErr(outputFile(args(2));
      Class app = Class.forName(args[0]);
      Method main = app.getDeclaredMethod("main", new Class[] { (new String[1]).getClass()});
      String[] appArgs = new String[args.length-3];
      System.arraycopy(args, 3, appArgs, 0, appArgs.length);
      main.invoke(null, appArgs);
   }
   protected PrintStream outputFile(String name) {
       return new PrintStream(new BufferedOutputStream(new FileOutputStream(name)), true);
   }
}

您使用 3 个附加参数调用它 - 要运行的 Main 类,以及输出/错误指示.

You invoke it with 3 additional params - the Main class to run, and the output/error directs.

这篇关于System.out 到 java 中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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