2

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

2 Answers2

4

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();
Karup
  • 2,024
  • 3
  • 22
  • 48
1

Consult this answer for better clarification redirect to file

public static void main(String[] args) {
    try {
        System.setOut(new PrintStream(new File("d:/output.txt")));
        System.out.println("StackOverflow");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
Community
  • 1
  • 1
Anurag Anand
  • 500
  • 1
  • 7
  • 13