David Marks Staff asked 4 years ago

How can a program be written

How can a program be written so that it opens a local file C:\DataDirectory\data.txt, reads in the data into the program without removing the data from the file, and appends new data onto the end of the existing data in the program and within the file?

For example, if the data file originally contained the data ‘Hello’, then when the program is done, it should say ‘Hello Hello my name is Bob’.

I also need to utilize exception handling technique to validate that the file has been open, and offer the user a chance to enter a correct filename until the file is found.

The hint I’ve been given is to use the overloaded open functions, or use random access methodology.

Thanks!

1 Answers
David Marks Staff answered 4 years ago

Assuming that you are writing this program in Java, you may use file reader along buffered Reader with path to the file in the format given below :-
C:/datadirectory/data.txt
Once the file is read, you may then use filewriter along with bufferedwriter to write to the same file.
Note:-
1) Use string variable to store the new content to be added and then use it as an argument while writing to the buffered writer.
2) use true as second argument to file writer to append the new content to the file name used as first argument.
3) Buffered writer is used to improve performance.
4) Enclose file reader and writer statement within try block to implement exception handling.