这是关于java序列化的问题。 首先,我粘贴我的代码。
import java.io.*;
public class Admin implements Serializable{
private static final long serialVersionUID = 613659699548582156L;
private String user;
private String password;
@Override
public String toString() {
return "{class:'Admin'" +
", user:'" + user + '\'' +
", password:'" + password + '\'' +
'}';
}
public Admin(String user, String password) {
this.user = user;
this.password = password;
}
public Admin() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean equals(Object o){
if (o == null) {
return false;
}
if (this == o) {
return true;
}
Admin admin = (Admin) o;
return (user != null ? user.equals(admin.getUser()) : admin.getUser() == null) &&
(password != null ? password.equals(admin.getPassword()) : admin.getPassword() == null);
}
public static void main(String[] args) {
//write object
// try {
// ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(Admin.class.getClassLoader().getResource("admin.out").getPath()));
// Admin a = new Admin("longlongago", "longlongago");
// out.writeObject(a);
// out.flush();
// out.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//read object
try {
ObjectInputStream in = new ObjectInputStream(Admin.class.getClassLoader().getResourceAsStream("admin.out"));
Admin a = (Admin) in.readObject();
System.out.println(a.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2353)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2822)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
at pw.loveyouforever.Model.Admin.main(Admin.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
当我复制或重命名文件时,它会显示为java.io.EOFException
。 即使我将文件名更改为以前的名称,它仍会显示java.io.EOFException
。只更改了文件名,文件的数据不会发生变化。为什么我不能读取此文件中的对象?