Search code examples
javafilestream

Is there a way to redirect the print statements in a Java program to required text files?


How to copy the contents of a print statement of a Java program to a text file using Print Stream?


Solution

  • I use the following code to do that from some time now. It works fine. There might be a better way.

    PrintStream ps = new PrintStream("\file.txt");
    PrintStream orig = System.out;
    System.setOut(ps);
    //TODO: stuff with System.out.println("some output");
    System.setOut(orig);
    ps.close();