序列化集合
import java.io.*;
import java.util.ArrayList;
import java.util.jar.JarOutputStream;
public class Demo22 {
public static void main(String[] args) {
ArrayList<Student> studentArrayList = new ArrayList<>();
studentArrayList.add(new Student("孙悟空", 18, "male"));
studentArrayList.add(new Student("鲁班七号", 19, "female"));
studentArrayList.add(new Student("姜子牙", 13, "male"));
studentArrayList.add(new Student("李白", 21, "female"));
serial(studentArrayList);
ObjectInputStream objectInputStream = null;
File file = new File("E:\\list.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
objectInputStream = new ObjectInputStream(new FileInputStream(file));
} catch (IOException e) {
e.printStackTrace();
}
try {
ArrayList<Student> list = (ArrayList<Student>) objectInputStream.readObject();
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getUsername() + "-" +
list.get(i).getAge() + "-" +
list.get(i).getGender());
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void serial(ArrayList<Student> studentArrayList) {
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream("E:\\list.txt"));
} catch (IOException e) {
e.printStackTrace();
}
try {
objectOutputStream.writeObject(studentArrayList);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}