System.out到Java中的文件

我正在从另一个应用程序内部运行一个应用程序以进行测试。我想将经过测试的应用程序的输出重定向到文件,因此每次测试后都可以有一个日志。

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


慕桂英546537
浏览 553回答 3
3回答

慕后森

您可以使用Windows命令行* nix shells支持的输出流重定向器,例如java -jar myjar.jar > output.txt另外,当您从vm内部运行应用程序时,可以System.out从java本身内部进行重定向。您可以使用方法System.setOut(PrintStream ps)它将替换标准输出流,因此所有对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类,然后输出/错误指示。

肥皂起泡泡

使用此构造函数时:new PrintStream(new BufferedOutputStream(new FileOutputStream(“ file.txt”))));记住将autoflushing设置为true,即:new PrintStream(new BufferedOutputStream(new FileOutputStream(“ file.txt”)),true);否则,即使程序完成后,您也可能会得到空文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java