So I am creating a program which will keep track of the TV shows and Movies that I watch. I have 2 classes (TV and Movie) and I have an Array which holds everyone. How would i go about saving this array so that every time I use the program it lets me edit the same list, because every time I watch a new episode I want to update my array with the new information. So basically what procedure would I need to use in order to not only save an arrya but load up the array every time I run the program?
问题:
回答1:
In order to save an array for further reference you need to make the class serializable (for example, by implementing Serializable
). What this means is that an object can be converted to a sequence of bytes which could be saved to a file or sent over the network, which can later be used to recreate the object in memory
Then you can do this to save the data to a file:
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("myarray.ser")
);
out.writeObject(myArray);
out.flush();
out.close();
You can read it back like this:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("myarray.ser"));
MyType[] array = (MyType[]) in.readObject();
in.close();
回答2:
While you could serialize your object and write it to disk... I am guessing it would be easier for you to simply output your array to a file and read it back in. You can write each element in the array to the file in a loop fairly easily, and read it back in just as easily. And like the others said, it is worth your time to look into an ArrayList or similar structure! Example:
To write to a file:
ArrayList<String> list = new ArrayList<String>();
// add stuff the the ArrayList
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("data.txt")));
for( int x = 0; x < list.size(); x++)
{
out.println(list.get(x));
}
out.close()
To read from a file:
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(new File("data.txt"));
while(scan.hasNext())
{
list.add(scan.next());
}
回答3:
Firstly, you should avoid arrays like the plague... use Collections
instead, which apart from anything else expand in size automatically as needed (you'll need this).
Regardless of whether you use array or a List
you can serialize the object to disk by writing the object to an ObjectOutputStream
wrapping a FileOutputStream
.
Note that the objects in the array/List must implement Serializable
, as must all your class fields.
To read the array/List back in, read from an ObjectInputStream
wrapping a FileInputStream
.
You can Google for the countless examples of such code.