gpt4 book ai didi

java - 尝试读取对象的 ArrayList 并将其写入二进制文件,但最终在输出中得到空值

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:02 26 4
gpt4 key购买 nike

所以我有一个名为 Human 的类,它只是我的另一个类“Admin”将继承的父类,这是代码,任何帮助将不胜感激当以更简单的形式完成时,拥有一个 Admin 类并在 main 中而不是 human 中创建 ArrayList ,它似乎工作得很好。

人类类:

package binaryfiles;

import java.util.ArrayList;


public class Human {


public ArrayList <Admin> myArrayList = new ArrayList <Admin> ();

private int Id;
private String Fullname;
private String Password;

public Human(){


}

public Human(int Id,String Fullname,String Password){

this.Id = Id;
this.Fullname = Fullname;
this.Password = Password;

}

public boolean setId(int Id){

if (Id > 0){

this.Id = Id;
}
return true;
}

public boolean setFullname(String Fullname){

if(Fullname != null){

this.Fullname = Fullname;

}
return true;
}

public boolean setPassword(String Password){

if(Password != null){

this.Password = Password;
}
return true;
}

public int getId(){

return Id;
}

public String getFullname(){

return Fullname;
}

public String getPassword(){

return Password;
}

}

这是 Admin 类:

public class Admin extends Human implements Serializable {


public void Binaryfile (int Id, String Fullname,String Password) throws FileNotFoundException, IOException, ClassNotFoundException{

Admin myAdmin = new Admin();
myAdmin.setId(Id);
myAdmin.setFullname(Fullname);
myAdmin.setPassword(Password);
myArrayList.add(0, myAdmin);

ObjectOutputStream Bin = new ObjectOutputStream(new FileOutputStream("D://testingfash5.bin"));
Bin.writeObject(myArrayList);
Bin.close();

ObjectInputStream Bout = new ObjectInputStream (new FileInputStream("D://testingfash5.bin"));
ArrayList <Admin> myArrayList2 = (ArrayList <Admin>)Bout.readObject();
System.out.println(myArrayList2.get(0).getId() + "-" +myArrayList2.get(0).getFullname()+ "-" + myArrayList2.get(0).getPassword());


}


}

最后这是我的主要内容:

public class BinaryFiles {

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {

Scanner Input = new Scanner(System.in);
int age;
int id;
String fullname;

Admin myAdmin = new Admin();
age = Input.nextInt();
fullname = Input.next();
id = Input.nextInt();
myAdmin.Binaryfile(id, fullname, fullname);


}
}

输出:“0- null - null

最佳答案

出现此问题的原因是您的父类 Human 不可序列化。添加以下行

class Human implements Serializable {

现在您将获得预期的输出。

关于java - 尝试读取对象的 ArrayList 并将其写入二进制文件,但最终在输出中得到空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53351532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com