Writing to console and text file

元气小坏坏 提交于 2019-11-27 01:46:32
Pshemo

Updated answer after learning that OP wants to duplicate streams

Since you want to write data in both streams try using TeeOutputStream from Apache Commons. Change your code in second try to

try {
    FileOutputStream fos = new FileOutputStream(f);
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            fos.flush();
        }
        catch (Throwable t) {
            // Ignore
        }
    }, "Shutdown hook Thread flushing " + f));
    //we will want to print in standard "System.out" and in "file"
    TeeOutputStream myOut=new TeeOutputStream(System.out, fos);
    PrintStream ps = new PrintStream(myOut, true); //true - auto-flush after println
    System.setOut(ps);
} catch (Exception e) {
    e.printStackTrace();
}

Now results from System.out will also be placed in your file.

In System.java, this is the declaration of the out property:

public final static PrintStream out

You'll see that it can only be one PrintSteam object at a time. So it's either the console or the file, but not both.

At this line, you have effectively re-channelled the destination:

System.setOut(ps);

So your output stops displaying on the console.

The reason is :

The java.lang.System.setOut() method reassigns the "standard" output stream.

so when you use System.out.println it will print only in the text file

So , if you want to print on the text file and on the console , Try this :

   

    FileOutputStream fos = new FileOutputStream(f);
    PrintStream ps = new PrintStream(fos);
    ps.println("THIS is what I see on the text file, but not on CONSOLE");
    System.out.println("THIS is what I see on the text file, but not on CONSOLE");

        for (int i = 0; i < 4; i++) {

            ps.println("Testing");
            System.out.println("Testing");
        } 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!