2

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?

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
  • possible duplicate of [File Write - PrintStream append](http://stackoverflow.com/questions/8043356/file-write-printstream-append) – Brian Jan 28 '13 at 21:00

4 Answers4

6

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);
Frank
  • 16,476
  • 7
  • 38
  • 51
2

Use

OutputStream printStream = new OutputStream(new FileOutputStream("someText.txt", true));
System.setOut(printStream);
Petr Mensik
  • 26,874
  • 17
  • 90
  • 115
1

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

vijay
  • 2,646
  • 2
  • 23
  • 37
0

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. :-)

C. K. Young
  • 219,335
  • 46
  • 382
  • 435