天天看點

Object————2

public class dajhsd{

public static void main(String[] args){

List<Fruit> fruitList = new ArrayList<Fruit>();

Fruit fruit= null;

try {

ObjectOutputStream ois = new ObjectOutputStream(new FileOutputStream("fruit.txt"));

ois.writeObject(new Fruit("apple",0.3,"red"));

ois.writeObject(new Fruit("apple",0.3,"red"));

ois.writeObject(new Fruit("apple",0.3,"red"));

ois.writeObject(new Fruit("apple",0.3,"red"));

ois.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

try {

ObjectInputStream oos = new ObjectInputStream(new FileInputStream("fruit.txt"));

while((fruit = (Fruit)oos.readObject()) != null){

fruitList.add(fruit);

}

}catch(EOFException e){

for(Fruit fruit_1 : fruitList){

System.out.println(fruit_1.getName());

}

}

catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}