JAVA ReDirect System.out.Println() to file

Re-directing System output is a simple task. Place the following method in your class:

private void redirectSystemOutput(){
             File file  = new File(“C:/SYSOUT.txt”);
             PrintStream printStream = new PrintStream(new FileOutputStream(file));
         }catch(Exception e){}         

 And call the method from the top of your application:



This will re-direct any instance of System.out.println() to a text file on Root C called SYSOUT.txt.
A very usefull monitor tool.

in a Swing application you can read this TXT file into an object such as a JTextArea.



Re-directing the output from the PrintStackTrace method is a bit more difficult.

Add the following method into your class:

public static String stack2string(Exception e) {
      try {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        return “——\r\n” + sw.toString() + “——\r\n”;
      catch(Exception e2) {
        return “bad stack2string”;

This will convert the PrintStackTrace element to a JAVA String.

Now, wherever you use the PrintStackTrace method, replace it with the following command:

   try {           
            //CODE TO RUN            
        } catch (Exception ex) {

This coupled with the re-direction of the System.Out.Println() method outlined above, will direct all output (System.out AND PrintStackTrace) to SYSOUT.txt on Root C.