On the output part of my IDE (where all the system.out.println textx appear), I have several lines of text. I want to get them and save them to a text file. What would be the possible code for this?
            Asked
            
        
        
            Active
            
        
            Viewed 675 times
        
    -2
            
            
        - 
                    Well somewhere in your code you must have defined the `System.out.println` arguments. take them? – PKlumpp Jun 13 '14 at 07:22
- 
                    [Start reading](http://stackoverflow.com/questions/2885173/java-how-to-create-and-write-to-a-file) – Alexandru Cimpanu Jun 13 '14 at 07:23
- 
                    http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#setOut(java.io.PrintStream) – JamesB Jun 13 '14 at 07:23
- 
                    Have a look at [this example](http://stackoverflow.com/questions/22241024/system-out-println-redirection-in-java/22241169#22241169) and [this example](http://stackoverflow.com/questions/18859410/dynamically-run-java-code-with-process/18860632#18860632) and [this example](http://stackoverflow.com/questions/12945537/how-to-set-output-stream-to-textarea/12945678#12945678) – MadProgrammer Jun 13 '14 at 07:24
2 Answers
2
            
            
        use System#setOut() to redirect output to FileOutputStream to redirect System output to file 
 // for restore purpose 
 PrintStream oldOutStream = System.out;
 PrintStream outFile = new PrintStream(
            new FileOutputStream("/path/to/file.txt", true));
 System.setOut(outFile);
 System.out.println("this will goto file");
I assume you know about logging framework and you are not trying to use this for logging something
 
    
    
        jmj
        
- 237,923
- 42
- 401
- 438
0
            
            
        Yo can replce all sop with fileoutput strem and write everything in file
if you want to write log then you can use log4j
String content = "This is the content to write into file";
File file = new File("filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
    file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
 
     
    