0

I need to print new information in a text file every fixed time, but when I try to do this, I find that it always clears the original file.

Here is my code segment:

public static class writeText implements Runnable {

    private File file;
    private QueueArray queue;

    public writeText(File file, QueueArray queue) {
        this.file = file;
        this.queue = queue;
    }

    @Override
    public void run() {
        try (PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "gb2312"), true)) {
            for (int i = 0; i < 100; i++) {
                if (queue.isQueueEmpty()) {
                    Thread.sleep(1000);
                    System.out.println("queue is empty........");
                } else {
                    output.println(writeCount++ + " " + queue.dequeue());
                    output.println();
                    output.println();
                    output.println();
                    output.println();
                    output.flush(); // force the data in the buffer to fill in the .txt

                    System.out.println("Writing the data successfully......");
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

What should I do to avoid this problem?

Tom
  • 16,842
  • 17
  • 45
  • 54
Calvin.Xie
  • 77
  • 1
  • 1
  • 8

1 Answers1

-1

If you wish to append data to the file instead of overwriting it, change

PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), "gb2312"),true);

to

PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file, true), "gb2312"),true);
Eran
  • 387,369
  • 54
  • 702
  • 768