开发者

Java console output - File And to Console BOTH

Probably this thread is a duplicate but can someone guide? I want to write the java program output to console and file at the same time. I know that i can send output to console开发者_高级运维 with this piece of code

    PrintStream orgStdout = null;
    PrintStream fileStdout = null;

    orgStdout = System.out;
    try {
        fileStdout = new PrintStream(new FileOutputStream("C:\\testlogger.txt"));
        System.setOut(fileStdout);
        System.out.println("==============");
        for (int i = 0; i < 10; i++){
            System.out.println("" + i);
        }
        System.out.println("==============");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

but how to keep output on console and on file as well??

P.S: not looking for an option where i output in file and display it console in different thread.


Look for TeeOutputStream from Apache Commons IO.


Don't call System.setOut(), and just make two calls to print. It's not very elegant, but you could make a method that outputs to both.

PrintStream orgStdout = null;
PrintStream fileStdout = null;

orgStdout = System.out;
try {
    fileStdout = new PrintStream(new FileOutputStream("C:\\testlogger.txt"));
    System.out.println("==============");
    for (int i = 0; i < 10; i++){
        System.out.println("" + i);
        fileStdout.println("" + i);
    }
    System.out.println("==============");
    fileStdout.println("" + i);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

If you're running on a unix box, you could also use the tee command as long as everything is printed to stdout. You'd run your program like this:

java MyClass | tee testlogger.txt

Then everything printed to stdout goes to both the file and console.


when you run your program

java {flags to the JVM} ClassName {parameters to your class} > output.txt 2> error.txt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜