Java中如何从文件中读取对象

时间:2020-02-23 14:34:22  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中从文件中读取对象。
在最后一篇文章中,我们已经看到了如何将对象写入文件并创建员工。

在本教程中,我们将读取相同的文件并检索员工对象。

从文件读取对象的步骤是:

使用ObjectInputStream读取来自文件的对象可以称为Deserialization。

允许举个例子:在src-> org.igi.theitroad中创建employee.java和exclate。

1.Employee.java.

package org.igi.theitroad;
import java.io.Serializable;
public class Employee implements Serializable{ 
   private static final long serialVersionUID = 1L;    
  int employeeId;
    String employeeName;
    String department;
    
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public String getDepartment() {
        return department;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
}

在src-> org.igi.theitroad 2.deserializemain.java中创建deserializemain.java

package org.igi.theitroad;
import java.io.IOException;
import java.io.ObjectInputStream;
 
public class DeserializeMain {
 /**
  * @author igi Mandliya
  */
 public static void main(String[] args) {
  
  Employee emp = null;
       try
       {
          FileInputStream fileIn =new FileInputStream("employee.ser");
          ObjectInputStream in = new ObjectInputStream(fileIn);
          emp = (Employee) in.readObject();
          in.close();
          fileIn.close();
       }catch(IOException i)
       {
          i.printStackTrace();
          return;
       }catch(ClassNotFoundException c)
       {
          System.out.println("Employee class not found");
          c.printStackTrace();
          return;
       }
       System.out.println("Deserialized Employee...");
       System.out.println("Emp id: " + emp.getEmployeeId());
       System.out.println("Name: " + emp.getEmployeeName());
       System.out.println("Department: " + emp.getDepartment());
 }
}

3.运行:

当我们在DeserializeMain.java上面运行时,我们将获取以下输出:

Deserialized Employee...
Emp id: 101
Name: igi
Department: CS