简体   繁体   中英

Java redirect System.out and appending

In Java, I have redirected System.out : System.setOut("someText.txt"); to write to a text file. I would like to run this program once an hour, and would like to append each set of print statements to the end of the file. For example suppose at hour 1, my program runs, prints "Hello\\n" and then quits. Then at hour 2, my program runs, prints "hello again\\n", and then quits.

If this happened I would like the contents of my text-file to be something like:

Hello
Hello again

Currently, I am just overwriting the text file.

  1. How can I append to the end of the text file with this redirected printStream?

EDIT How can I also print to the console?

When you build the FileOutputStream use the following:

FileOutputStream(File file, boolean append)

Creates a file output stream to write to the file represented by the specified File object.

from the JAVADOC

Code example:

OutputStream outStream = new FileOutputStream("file1.txt",true);

Use

OutputStream printStream = new OutputStream(new FileOutputStream("someText.txt", true));
System.setOut(printStream);

the answers by @Frank and @Petr Mensik are correct. But just in case you wanted to try something different:

System.out.append("Hello World\\n") should do the trick. Hence, instead of doing a System.out.print , you do a System.out.append

The simplest answer is not to do this using Java code, but to use tee ; trying to reimplement tee in Java is just reinventing a square wheel. Just do this:

java -jar yourapp.jar | tee -a output.log

On Windows? Install MinGW and/or Cygwin. :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM