在这个例子中,我们将使用ObjectOutputStream类将雇员对象写入文件。
java.io.Serializable
接口的子类,否则write()
方法就会出现1d2d1e。java.io.Serializable
接口。让我们首先创建Employee
类,它实现了a java.io.Serializable
接口。
class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
让我们在某个目录下创建an employees.txt
文件。写代码将雇员对象写入employees.txt
文件。
/**
* This Java program demonstrates how to write object in file.
* @author javaguides.net
*/
public class ObjectOutputStreamExample {
public static void main(String[] args) {
final Employee employee = new Employee();
employee.setId(100);
employee.setName("ramesh");
try (final FileOutputStream fout = new FileOutputStream("employees.txt");
final ObjectOutputStream out = new ObjectOutputStream(fout)) {
out.writeObject(employee);
out.flush();
System.out.println("success");
} catch (IOException e) {
e.printStackTrace();
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/07/how-to-write-object-to-file-in-java.html
内容来源于网络,如有侵权,请联系作者删除!