Using ObjectOutputStream:
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.ObjectOutputStream;
- import java.io.Serializable;
- class Employee implements Serializable {
- private static final long serialVersionUID = 1L;
- int id;
- String name;
- double salary;
- // transient double salary;
- public Employee(int id, String name, double salary) {
- this.id = id;
- this.name = name;
- this.salary = salary;
- }
- @Override
- public String toString() {
- return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
- }
- }
- public class WriteByObjectOutputStreamExe {
- public static void main(String[] args) throws Exception {
- File file = new File("D:\\data1.txt");
- FileOutputStream fileStream = new FileOutputStream(file);
- ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
- Employee e1 = new Employee(101, "suresh", 2000);
- objStream.writeObject(e1);
- objStream.flush();
- objStream.close();
- }
- }
Output:
ͭ sr com.ishaan.filehandling.Employee I idD salaryL namet Ljava/lang/String;xp e@ࠀ t suresh
No comments:
Post a Comment