Java中如何将对象写入文件
时间:2020-02-23 14:34:24 来源:igfitidea点击:
如果要在网络上发送对象,则需要将对象写入文件并将其转换为流。
该过程可以称为序列化。
对象需要实现序列化接口,该接口是标记接口接口,我们将使用java.io.ObjectOutputStream将对象写入文件。
让我们通过步骤来将对象写入文件。
让我们举个例子:创建员工。
java在src-> org.igi.theitroad
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;
}
}
如上所述,如果要序列化任何类,那么它必须实现序列化接口,这是标记接口。
Java中的标记接口是没有字段或者方法的接口,或者在简单的单词中,Java中的空接口被称为标记接口在SRC-> org.igi.onitoad中创建SerializeMain.java
2.SerializeMain.java.
package org.igi.theitroad;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializeMain {
/**
* @author igi Mandliya
*/
public static void main(String[] args) {
Employee emp = new Employee();
emp.setEmployeeId(101);
emp.setEmployeeName("igi");
emp.setDepartment("CS");
try
{
FileOutputStream fileOut = new FileOutputStream("employee.ser");
ObjectOutputStream outStream = new ObjectOutputStream(fileOut);
outStream.writeObject(emp);
outStream.close();
fileOut.close();
}catch(IOException i)
{
i.printStackTrace();
}
}
}
当我们运行上面的程序时,员工将创建。
它的内容不会处于人类可读格式,但它将具有存储在文件上的对象。
我们可以使用ObjectInputStream从文件中读取同一对象。

