System.out 到 java 中的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2851234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:38:56  来源:igfitidea点击:

System.out to a file in java

java

提问by Carlos Blanco

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.

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

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

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

采纳答案by mdma

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

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

java -jar myjar.jar > output.txt

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

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

System.setOut(PrintStream ps)

System.setOut(PrintStream ps)

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"))));

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

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.

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

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);
   }
}

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

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

回答by vijay.shad

Yes you can set your desired file like this.

是的,您可以像这样设置所需的文件。

try {
    System.setOut(new PrintStream(new File("output-file.txt")));
} catch (Exception e) {
     e.printStackTrace();
}

回答by Jagoliveira

In order to improve "vijay.shad" response I used the code bellow to direct the file to the Home Directory in Linux or MyDocuments in Windows.

为了改进“vijay.shad”响应,我使用下面的代码将文件定向到 Linux 中的主目录或 Windows 中的 MyDocuments。

    try {
        System.setOut(new PrintStream(new File(FileSystemView.getFileSystemView()
                .getDefaultDirectory().toString()
                + File.separator + "output-file.txt")));
    } catch (Exception e) {
         e.printStackTrace();
    }

回答by psu

When using this constructor:

使用此构造函数时:

new PrintStream(new BufferedOutputStream(new FileOutputStream("file.txt")));

remember to set autoflushing to true, i.e.:

记得将 autoflushing 设置为 true,即:

new PrintStream(new BufferedOutputStream(new FileOutputStream("file.txt")), true);

otherwise you may get empty files even after your program finishes.

否则,即使在程序完成后,您也可能会得到空文件。

回答by Rajesh Dixit

System.out.println() is used to print messages on the console.

System.out.println() 用于在控制台上打印消息。

System is a class defined in the java.lang package. out is an instance of PrintStream, which is a public and static member of the class System. As all instances of PrintStream class have a public method println().

System 是在 java.lang 包中定义的一个类。out 是 PrintStream 的一个实例,它是类 System 的公共和静态成员。因为 PrintStream 类的所有实例都有一个公共方法 println()。

System.outis a static PrintStreamthat writes to the console. We can redirect the output to a different PrintStream using the System.setOut()method which takes a PrintStream as a parameter.

System.out是写入控制台的静态 PrintStream。我们可以使用System.setOut()方法将输出重定向到不同的 PrintStream,该方法将 PrintStream 作为参数。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class SetPrintStream {
  public static void main(String[] args) throws FileNotFoundException{
           System.out.println("Print on console");

           // Store console print stream.
           PrintStream ps_console = System.out;

           File file = new File("file.txt");
           FileOutputStream fos = new FileOutputStream(file);

           // Create new print stream for file.
           PrintStream ps = new PrintStream(fos);

           // Set file print stream.
           System.setOut(ps);
           System.out.println("Print in the file !!");

           // Set console print stream.
           System.setOut(ps_console);
           System.out.println("Console again !!");
 }
}

Output:
Print on console
Console again !!
new file.txt will be created.

For more information see my blog:

更多信息请看我的博客:

http://javaexplorer03.blogspot.in/2016/02/how-do-i-redirect-standard-output-to.html

http://javaexplorer03.blogspot.in/2016/02/how-do-i-redirect-standard-output-to.html

回答by omkar sirra

    File file = new File("xyz.txt");        
    PrintStream printStreamToFile = new PrintStream(file);
    System.setOut(printStreamToFile);
    System.out.println("Hello I am writing to File xyz.txt");