Sunday, April 29, 2018

Write data in a file using ObjectOutputStream !!

Using ObjectOutputStream:
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.ObjectOutputStream;
  4. import java.io.Serializable;

  5. class Employee implements Serializable {

  6. private static final long serialVersionUID = 1L;
  7. int id;
  8. String name;
  9. double salary;
  10. // transient double salary;

  11. public Employee(int id, String name, double salary) {
  12. this.id = id;
  13. this.name = name;
  14. this.salary = salary;
  15. }

  16. @Override
  17. public String toString() {
  18. return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
  19. }
  20. }

  21. public class WriteByObjectOutputStreamExe {

  22. public static void main(String[] args) throws Exception {
  23. File file = new File("D:\\data1.txt");
  24. FileOutputStream fileStream = new FileOutputStream(file);
  25. ObjectOutputStream objStream = new ObjectOutputStream(fileStream);

  26. Employee e1 = new Employee(101, "suresh", 2000);

  27. objStream.writeObject(e1);
  28. objStream.flush();
  29. objStream.close();
  30. }
  31. }
Output:
ͭ sr  com.ishaan.filehandling.Employee        I idD salaryL namet Ljava/lang/String;xp   e@ࠀ     t suresh


No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...