I am working on a project for my advanced Java class, and the assignment says he wants us
to send an object to a file, which is easy enough, but that he also wants the file to be human readable and editable. I sent him an e-mail 3 days ago and he hasn’t responded, so
I am kind of stuck between a rock and hard place since the project is due in 3 days.
So would any of you clever programmers be able to fill me in on the secret that apparently I am left out of.
How do you send an object to a file that reads like English?
I want to have the ability to both read and write a to-do item to a
file. I see our application looking like:
- When it first starts, the program asks the user if there is a file containing to-do items. If so, the user will name the file, the
program will read it in and continue.- When the user decides to exit, the program will prompt the user – to ask if the to-do items should be saved to a file – if so, the
user will name the file and the program will write them out in
such a fashion that it can read them in again.I want these file to be human readable (and editable). No binary data.
No counting. My advice to you would be to have a method somewhere that
looked like:public ToDoItem getToDoItem(FileInputStream fis) { // ... }and
public void writeToDoItem(FileOutputStream fos) { // ... }
Think how you would represent an object on paper in such a way that it could be reconstructed unambiguously. You’d probably list the class name, then you’d list each field name and its current value. If the field was a primitive, the value would be just the primitive value. If it was a reference type, you’d represent the object recursively using this procedure. If it was an array, you’d list each element value.
There are various standard ways of formatting such a representation (XML and JSON to name a couple). The key is to make it a text-only representation so it is human-readable.