You can never use a PrintStream
to accomplish this task in the way you are doing it. The API clearly states that the constructor of the PrintStream
does the following:
PrintStream(File file)
Creates a new print stream, without automatic line flushing, with the specified file.
file - The file to use as the destination of this print stream. If the
file exists, then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
There are no constructors that allow you to append to the previous file.
The solution therefore lies in the fact that you can only use the PrintStream
constructor exactly ONCE. This can be achieved by making your output
variable a class variable and getting rid of your declaration (as well as the try-catch) in decideOutcome()
.
private static PrintStream output;
public static void main(String[] args) {
try {
output = new PrintStream(new File("records.txt"));
execute();
} catch (FileNotFoundException e) {
System.out.println("File was not found; try again");
} finally {
output.close();
}
}
Another important thing to note is that whenevre you open a stream such as a Scanner or a PrintStream you should always close it. The best place to close them is in a finally
clause as that part of your code is guaranteed to run.