我有序列化的问题...我测试这个方法与类分开并正常工作!但是当我使用这个课时,得到NotSerializableException
代码:
必须序列化的属性:
public ArrayList<User> users;
此属性位于UserManage
class
此方法用于从数据库文件中读取:
public void readFromDataBaseFile(){
File database=new File(this.saveUsersObject+"\\"+"Database.txt");
if(!database.exists()){
System.out.println("Exception:FileNotExist");
}
else{
HashMap<String,Object> Data=(HashMap<String,Object>)FileHandler.readObjectInFile(database);
this.users= (ArrayList) Data.get("users");
}
}
这种写入数据库文件的方法:
public void writeToDataBaseFile(){
File database=new File(this.saveUsersObject+"\\"+"Database.txt");
if(!database.exists()) {
File parent=database.getParentFile();
parent.mkdirs();
}
HashMap<String,Object> Data=allOfUsersToHashMap();
if(Data.isEmpty()){
System.out.println("DataBase HashMap Is Empty!");
}
else{
FileHandler.writeObjectInFile(Data,database);
}
}
上述方法属于班级UserManage
。
下面的方法是在文件中写入对象的辅助方法:
boolean writeObjectInFile(Object obj,File file)
:public static boolean writeObjectInFile(Object obj,File file){
String Path=file.getAbsolutePath();
if(file.exists()){
System.out.println("Object File Was Deleted!!");
file.delete();
}
else{
try
{
FileOutputStream fileOut = new FileOutputStream(Path);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved To :"+file.getPath());
return true;
}catch(IOException i)
{
i.printStackTrace();
}
}
return false;
}
以下方法是从文件中读取对象的辅助方法:
Object readObjectInFile(File file)
: public static Object readObjectInFile(File file) {
Object obj=null;
if(file.isFile()){
try
{
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
System.out.println(file.getAbsoluteFile());
obj=in.readObject();
fileIn.close();
in.close();
System.out.printf("DeSerialized data is Done From:"+file.getPath());
}catch(IOException i)
{
i.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
else {
System.out.println("returned null :\\");
System.out.println("Enter Address Of A File Not Folder Or Another! :\\");
}
return obj;
}
课程allOfUsersToHashMap()
中的方法UserManage
:
public HashMap<String,Object> allOfUsersToHashMap(){
HashMap<String,Object> Userdatabase=new HashMap<>();
Userdatabase.put("users",this.users);
return Userdatabase;
}
我必须说当ArrayList<User> user
为null时此方法正常工作但是当用户不工作时!
答案 0 :(得分:5)
如果User类未实现Serializable接口,则无法序列化ArrayList。有关实现的详细信息,请参阅JavaDoc for Serializable:https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html
答案 1 :(得分:1)
您的ok_btn.grid(row = 0, column = 3, sticky = 'ew', padx=(0, 8))
POJO是否符合序列化的所有要求?
检查上一个问题:What is object serialization?