- import java.io.EOFException;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class ObjectIOdemo {
- /**
- * @param args
- * @throws IOException
- * @throws ClassNotFoundException
- */
- public static void main(String[] args) throws IOException, ClassNotFoundException {
- writeObj();
- readObj();
- }
- public static void readObj() throws IOException, ClassNotFoundException {
- FileInputStream fis = new FileInputStream(new File("c:\\1.object"));
- ObjectInputStream ois = new ObjectInputStream(fis);
- //这段代码将出现EOFException异常
- // Object obj = null;
- // while((obj=ois.readObject()) != null) {
- // Person per = (Person)obj;
- // System.out.println(obj);
- // }
-
- try {
- while(true) {
- System.out.println(ois.readObject());
- }
- }catch(EOFException e) {
- System.out.println("已经读完所有对象");
- }
-
- ois.close();
- }
- public static void writeObj() throws IOException {
- FileOutputStream fos = new FileOutputStream(new File("c:\\1.object"));
-
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(new Person("xiaomin", 25));
- oos.writeObject(new Person("xiaoqiang", 26));
-
- oos.close();
- }
- }
复制代码
注释部分打开的话将会出现异常。
问题是 ObjectInputStream类不能用 readObject()方法(取到null)来判断取到最后一个对象吗?
虽然我可以用自己处理异常来解决,就想问一下,这是正常的解决方法不? |