A Java program to write to a text file using PrintWriter (not FileWriter).
This program reads in a text file using Scanner – a date and a boolean flag.
It adds 45 days to the date and compliments the flag (true to false and false to true)
It then writes the new data to a new file. You can open the new file in the projects folder. It will contain the new data if your remembered to close the file using the close command – this flushes the buffer.
There are two versions of this program shown below. The first uses “useDelimiter” while the second using the split method.
Click here for the split method
When writing to a text file you can overwrite the existing data (without append), or you can add the new data to the existing data (with append).
Writing to a text file without append
pw = new PrintWriter(new FileWriter(“newData.txt”)); // overwrites existing data
Writing to a text file with append
pw = new PrintWriter(new FileWriter(“newData.txt”, true)); // adds the new data to the existing data