第一个类:
private String name;
private String code;
ArrayList a = (ArrayList)in.readObject();
System.out.println(a.size());
for(int i = 0; i
System.out.println(a.get(i).getName()+","+a.get(i).getCode());
}
catch (ClassNotFoundException e) {
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class User implements
Serializable{
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public User(String name, String code) {
super();
this.name = name;
this.code = code;
}
public static void writeUser(ArrayList userList,File file){//file 为写入的文件
ObjectOutputStream oos;
try {
if(!file.exists())
file.createNewFile();
oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(userList);
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
第二个类(测试类)
import java.io.*;
import java.util.*;
public class testObjectStream {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList userList = new ArrayList();
for (int i = 0; i < 5; i++) {
User u = new User("java"+i, "#" + i);
userList.add(u);
}
File f = new File("d:\\m.txt");
User.writeUser(userList, f);
ObjectInputStream in;
try {
if(!f.exists())
f.createNewFile();
in = new ObjectInputStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}