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

查看:126
本文介绍了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 shell,例如

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

或者,当您从虚拟机内部运行应用程序时,您可以重定向 System.out 来自java本身。您可以使用方法

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天全站免登陆