【发布时间】:2016-05-07 00:03:17
【问题描述】:
您好,我正在学习泛型,我无法将文件中的对象反序列化为泛型列表然后打印。
结果是一个空白屏幕,即使我知道创建了一个 dat 文件
我尝试了多种方法。
我使用带有 ActionListener 的框架..
这是 ActionListener
private class AddButtonActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// variables
String inputfName;
String inputlName;
String idInput;
//String studentID;
// capture input
inputfName = sFirstName.getText();
inputlName = sLastName.getText();
idInput = sID.getText();
//hold Student data
//convert to Int
//studentID = Integer.parseInt(idInput);
//Create file
StudentAddProcess sFile = new StudentAddProcess();
sFile.writesFile(inputfName, inputlName, idInput );
}
这些处理输入
公共类 StudentAddProcess 实现 Serializable{
String inputFirstName ;
String inputLastName;
String inputID;
private Component Frame;
// Create File
public void writesFile ( String fName, String lName, String Id ){
// create T fields for student
inputFirstName = fName;
inputLastName = lName;
inputID = Id;
try {
ObjectOutputStream objectInputFile = new ObjectOutputStream(outStream);
//Linkeked List of Student Objects
GenericLinkedList<Student> studentList = new GenericLinkedList<>();
// add Student Object to student
studentList.add(new Student(inputID, inputFirstName, inputLastName));
//Where am i
JOptionPane.showMessageDialog(Frame, "writing ...");
// for loop cycle and write student to fill
for (int i =0 ; i < studentList.size();i++) {
objectInputFile.writeObject(studentList.get(i));
}
JOptionPane.showMessageDialog(Frame, "Complete :");
//close file
objectInputFile.close();
现在我们查看添加的对象
public class StudentViewFile implements Serializable {
//variables
private String studentID; // holds passed user request to view
private Component Frame;
public void readFile(String sID) throws IOException {
studentID = sID; // take passed variable
//int studentID2 =Integer.getInteger(sID);
try {
//open read file
FileInputStream inStream = new FileInputStream("StudentObjects.dat");// Stream of Objects
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
GenericLinkedList <Student> readRecord = new GenericLinkedList<>();
readRecord.add(new Student(studentID));
for (int i = 0; i < readRecord.size(); i++) {
readRecord = (GenericLinkedList) objectInputFile.readObject();
// Diplay records
System.out.println("File Objects" + readRecord.get(i) + " \n next positions");
// was going to try to print my test here
System.out.println(readRecord.toString());
}
// Read the serialized objects from the file.
while (true) {
readRecord = (GenericLinkedList) objectInputFile.readObject();
// Display records
System.out.println( "File Objects" + readRecord+ " \n next positions");
//close file
objectInputFile.close();
}
} catch (EOFException e) {
System.out.print("\n Exception caught ");
任何想法都会很棒。提前感谢您的时间和知识
【问题讨论】:
-
这不是问题,但
ObjectOutputStream objectInputFile =是一个奇怪的变量名选择!保证会让试图阅读您的代码的人感到困惑。 -
为什么要初始化并添加到您立即重新分配的列表中?
标签: java generics linked-list