出于测试目的,我正在从另一个应用程序内部运行一个应用程序。我想将测试应用程序的输出重定向到一个文件,这样我就可以在每次测试后都有一个日志。
有没有办法将应用程序的输出从 java 的命令行重定向到文件?
最佳答案
您可以使用 Windows 命令行支持的输出流重定向器,例如 *nix shells
java -jar myjar.jar > output.txt
或者,当您从 vm 内部运行应用程序时,您可以从 java 本身重定向 System.out
。你可以使用方法
它替换了标准输出流,因此对 System.out 的所有后续调用都转到您指定的流。您可以在运行包装的应用程序之前执行此操作,例如调用 System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream("output.txt"))));
如果您使用无法修改的包装器,请创建您自己的包装器。所以你有 FEST 包装器 -> 流重定向器包装器 -> 测试的应用程序。
例如,您可以像这样实现一个简单的包装器:
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 类,以及输出/错误指示。
关于java - System.out 到 java 中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2851234/