-
designing a save system
Hi,
So, I'm working on a little program that creates an array and then executes various algorithms on it. What I want to do though, is save the array in a .txt file so that I don't have to constantly re-enter the values after each run through the program.
This in my mind requires two classes:
1) to save the array
2) to load the array from a .txt file
Now, I have three questions:
1) Is this save/load model a good idea, or is there a more efficient way of doing this?
2) how do you convert the array to a string to print it, or how do you print an array to a text file? I'm guessing this involves some "for" loops that take each array data and then convert to string which is then written.
3) what would be the most efficient way to load an array? again I'm guessing "for" loops for each line and then assign's them as array values.
I guess this thread is more of a, making sure I get my design right before I spend hours working on it and then it doesn't work.
-
Normally if you want your data to persist you would use a database. However writing out to a flat file for something simple is fine.
You can either iterate over your array and write the data to a File using a FileWriter. Or you can use an ObjectOutputStream to write the entire array. Note the "save" file will not be human readable. So it will depend upon if you want to be able to read and modify the file. Use an ObjectInputStream to read the array back into your Java app.
-
Is it going to be gui based? I would just have action listeners to read/write.
1.) You could just use a method to load, and a method to save.
2.)What does the array contain? numbers? If so, it's easy to convert to strings. A for loop is the correct way to write the array to a text file, since you know how many items are in the array you can use for loops and a file stream and a print writer chained together.
3.)For loading the array you would probably use a while loop(although a for loop is fine too) and just read from the file storing each item in the correct array spot.
With saving/loading it will absolutely take some playing around with to get it right. Give it a shot and see how it works.
-
@junkie I'll look into those, since no the file does not need to be edited.
@sunde887, thanks for your reply, no this wont be gui based just good ole JVM in Eclipse and your right these should be two methods not classes. thanks :)
-
Your welcome. Whenever I am working on save load stuff it takes me a decent amount of trial and error(mainly since I'm inexperienced with it), finding which readers and writers and how to get the saves and loads working correctly.