Changing standard output in Java

Is there a way to change the standard output stream so that it is written to some file, and not to the console in Java ???

+3
source share
6 answers
+8
source

There are a few things you can do. To answer your question, you would do something like

System.setOut(new FileOutputStream(myFile));

However, I would use a registration framework to write to a file. First, initialize your registrar somewhere:

FileHandler handler = new FileHandler("mylogfile.txt", true); // True to append to file, false to overwrite.
Logger logger = Logger.getLogger(getClass().getName());
logger.addHandler(handler);

Then you can use the method that you call every time you want to print something, for example:

public void output(String message, boolean toConsole, boolean toFile) {
    if (toConsole) {
        System.out.println(message);
    }
    if (toFile) {
        m_logger.info(message); // Your instance variable of Logger.
    }
}

, , . toConsole toFile , .

+3

System.setOut(new PrintStream(file))

But using the logging method is much better.

+2
source

Take a look at System.setOut .

+1
source

You can use System.setOut()for this

0
source

The following works for me.

System.setOut (new PrintStream (new FileOutputStream (file name)));

0
source

All Articles