import java.io.*;public class TestExternalizable { public static void main(String[] args) {
Person p=new Person("ZYP",23);
try {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("G:\\1.txt"));
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("G:\\1.txt"));
oos.writeObject(p);
Object o=ois.readObject();
System.out.println(o);
oos.close();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}}class Person implements Externalizable {
    String name;
    int age;
    
    public Person() {
    
    }

public Person(String name, int age) {
this.name = name;
this.age = age;
} public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("读出");
this.name=in.readUTF();
in.readUTF();
this.age=in.readInt();

}
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("写入");
out.writeUTF("name");
out.writeUTF("------------");
out.write(age);

} public String toString() {
return "name="+name;
}


}
请问怎么会出错,如何解决错误,谢谢

解决方案 »

  1.   

    What is the error or exception? Show us...
      

  2.   

    写入
    读出
    java.io.EOFException
    at java.io.DataInputStream.readInt(DataInputStream.java:375)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:2776)
    at java.io.ObjectInputStream.readInt(ObjectInputStream.java:950)
    at Person.readExternal(TestExternalizable.java:43)
    at java.io.ObjectInputStream.readExternalData(ObjectInputStream.java:1792)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1751)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
    at TestExternalizable.main(TestExternalizable.java:11)这是这个程序的错误信息
      

  3.   

    文件尾异常,解决办法是:
    try { 
    ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("G:\\1.txt")); 
    ObjectInputStream ois=new ObjectInputStream(new FileInputStream("G:\\1.txt")); 
     .
     .
     .
    } catch (FileNotFoundException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
      if (e instanceof EOFException) {}
      else {
          e.printStackTrace(); 
      }
    } catch (ClassNotFoundException e) { 
    e.printStackTrace(); 

      

  4.   

    楼上两位大哥的方法是治标不治本,对异常不处理,并不代表它没有异常啊,程序还是会抛出EOFException。
    楼主的问题是写的东西和读取的东西不一致,writeExternal方法对年龄的写入用out.write(age),readExternal读取时用in.read()。
    也可使用writeInt(age),读取时使用,readInt()。
    问题就解决了。
      

  5.   

    使用Object数据流在网络间传输的时候 传输的对象必须实现序列化 即Serializable接口class Person implements Externalizable 将 Externalizable 换成Serializable试试