How to copy the contents of a print statement of a Java program to a text file using Print Stream?
            Asked
            
        
        
            Active
            
        
            Viewed 120 times
        
    2
            
            
        - 
                    1You mean from inside the program or when you are running it? – RealSkeptic Sep 09 '15 at 12:45
- 
                    @RealSkeptic : not clear with your question – SANTHOSH B.E Sep 09 '15 at 13:30
- 
                    You can redirect a program that writes to the default `System.out` when you run it (for example, on Linux/Mac, `java MyProgram > file.txt`), or you can change the `System.out` inside the program itself. So which of those options do you want? – RealSkeptic Sep 09 '15 at 13:57
- 
                    While running @RealSkeptic – SANTHOSH B.E Sep 10 '15 at 05:07
2 Answers
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
- 
                    uhmm... that makes more sense than my answer, I think I misunderstood the question.... +1 and deleting my answer!! – Jordi Castilla Sep 09 '15 at 12:48
- 
                    [http://stackoverflow.com/questions/14552342/redirect-lots-of-system-out-printlns-to-a-txt-file] Here is the original answer. Credits to @iainmackay85. It has helped me a lot! – Karup Sep 09 '15 at 12:50
- 
                    
- 
                    
- 
                    It does work for me. Perhaps you can add your code to your question so that I can look at it? – Karup Sep 09 '15 at 14:08
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
- 
                    
- 
                    yes ,but the answer by PuRak also working fine , is it possible to accept both the answers – SANTHOSH B.E Sep 09 '15 at 13:59
- 
                    @SANTHOSHB.E not possible to accept both the answers.. You should accept his answer.. Because his answer was posted earlier than my answer.. – Anurag Anand Sep 09 '15 at 14:03
