Writing to console and text file

后端 未结 3 1327
闹比i
闹比i 2020-11-29 08:44

I found the code below from the internet, works but it doesn\'t write the printed console to omt.txt, it only writes the System.out.println statements after the

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 09:36

    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.

提交回复
热议问题