help for solving a problem with java I/O
I have created a class named Animal with implements Serializable. Each object of the Animal class has a name and a type. In the Main method of my program, I will create an object of type Animal and assign a name and a type to it. then I want to write the object into a file and after that read read that file into an Animal object. for this aim I have created the following mthods:
Animal anim=new Animal开发者_JAVA百科();
Animal Anim2 = new Animal();
//writing into the file
private void writeOnFile() {
try{
FileOutputStream fout = new FileOutputStream("c:\\animal.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(anim);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
// reading the file
private Animal readFromFile() {
try{
FileInputStream fin = new FileInputStream("c:\\animal.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
anim = (Animal) ois.readObject();
ois.close();
return anim;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
but now I want to create a linkedList and add several objects of Animal into that linkedList. How can I change my writeOnFile() and readFromFile() methods to do the write work? would you please guide me?
Karianna's reply is good, using a foreach. But this homework apparently focuses on the features of the Serializable interface, so let's use it.
Since your Animal class implements Serializable as well as the LinkedList class you can simply pass your LinkedList to your ObjectOutputStream and load it in a similar manner.
LinkedList<Animal> list = new LinkedList<Animal>();
(... add some elements ...)
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(list);
The loading would be your part, as you want to learn something from this exercise, don't you ;)
karianna gave a good answer. I just want to add that Linked list itself implements serializable, so you can just write it to file and read it back. Just do not forget to wrap your output and input streams with ObjectOutputStream and ObjectInputStream.
That's it. Now implement your homework and learn something new!
Hint: You need to use a loop construct such as a for or while loop that will loop over your List of Animals. For example,
You'll need to declare your list of animals somewhere. Something like:
List<Animal> animals = new ArrayList<Animal>();
And loop over them, something like:
for (Animal animal:animals)
{
// Do appropriate thing
}
I'll leave the rest to you to fill out, I suspect you'll get more out of the exercise that way :-).
精彩评论