I am trying out serializing and deserializing a java application.
(我正在尝试序列化和反序列化Java应用程序。)
It's working but I would like to know if I am doing this process correctly. (它正在工作,但是我想知道我是否正确地执行了此过程。)
I am serializing the ArrayList; (我正在序列化ArrayList;)
is this the proper way or should I be serializing the Employee class, but how would I go about that considering we could have many employees? (这是正确的方法还是应该序列化Employee类,但是考虑到我们可能有很多员工,我将如何处理呢?)
The way I am doing it causes this error which I would like to get rid of:
(我这样做的方式导致此错误,我想摆脱它:)
serialTest.java:40: warning: [unchecked] unchecked conversion employees = (ArrayList) ois.readObject();
(serialTest.java:40:警告:[unchecked]未经检查的转换雇员=(ArrayList)ois.readObject();)
required: ArrayList found: ArrayList 1 warning (必需:找到ArrayList:ArrayList 1警告)
Here is the Employee class: package serialTest;
(这是Employee类:package serialTest;)
import java.io.Serializable; (导入java.io.Serializable;)
public class Employee implements Serializable {
int id;
String firstName;
String lastName;
public Employee(int id, String firstName, String lastName) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
And here is the main class:
(这是主要的类:)
package serialTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class serialTest {
static ArrayList<Employee> employees = new ArrayList<>();
public static void main(String[] args) {
if (args.length > 0) {
deSerialize();
} else {
employees.add(new Employee(1, "John", "Doe"));
employees.add(new Employee(2, "Jane", "Doe"));
serialize();
}
}
private static void serialize() {
System.out.println("Serializing...");
try {
try (FileOutputStream fos = new FileOutputStream("employeeData"); ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(employees);
}
} catch (IOException ioe) {
}
}
private static void deSerialize() {
System.out.println("DeSerializing...");
try {
try (FileInputStream fis = new FileInputStream("employeeData");
ObjectInputStream ois = new ObjectInputStream(fis)) {
employees = (ArrayList) ois.readObject();
}
} catch (IOException ioe) {
System.out.println("File problems");
return;
} catch (ClassNotFoundException c) {
System.out.println("Class problems");
return;
}
for (Employee info : employees) {
System.out.println(info);
}
}
}
ask by James Mead translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…