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?