Wednesday, February 10, 2010

Writing console output to a file in java

Use this code to write your console outputs to a file using java.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class RedirectIO {

public static void main(String[] args) {

PrintStream orgStream = null;
PrintStream fileStream = null;

try {

// Saving the orginal stream
orgStream = System.out;
fileStream = new PrintStream(new FileOutputStream("d:/123.txt",true));

// Redirecting console output to file
System.setOut(fileStream);

// Redirecting runtime exceptions to file
System.setErr(fileStream);

throw new Exception("Test Exception");

}catch (FileNotFoundException fnfEx){
System.out.println("Error in IO Redirection");
fnfEx.printStackTrace();
}catch (Exception ex){
ex.printStackTrace();
//Gets printed in the file
System.out.println("Redirecting output & exceptions to file");
}finally{
//Restoring back to console
System.setOut(orgStream);
//Gets printed in the console
System.out.println("Redirecting file output back to console");
}
}
}

2 comments:

  1. In file I have:
    java.io.FileInputStream@5b6afd

    ReplyDelete
  2. The body of your college essay must include compare and contrast, definitions and cause and effect examples, so that persons reading your essay will be better able to understand your concept. https://adamhuler.medium.com/what-is-the-best-essay-writing-service-on-reddit-f0f7832c99eb

    ReplyDelete