Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.out to a file in java

Tags:

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.

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

like image 429
Carlos Blanco Avatar asked May 17 '10 17:05

Carlos Blanco


People also ask

How do I send console output to a file?

To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.

Can System out Println () be used to write data to a file?

Invoke the out() method of the System class, pass the PrintStream object to it. Finally, print data using the println() method, and it will be redirected to the file represented by the File object created in the first step.

What is the System out in Java?

System. out. println is a Java statement that prints the argument passed, into the System. out which is generally stdout. System is a Class.


1 Answers

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 

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)

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

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

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

like image 76
mdma Avatar answered Sep 28 '22 11:09

mdma