Sunday, April 29, 2018

Read / Write data in a file for transient field using ObjectOutputStream

Using ObjectOutputStream class & transient keyword:
  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 idL namet Ljava/lang/String;xp   et suresh

Read transient field data from a file using ObjectInputStream:
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.ObjectInputStream;

  4. public class ReadFileByObjectInputStreamExe {

  5. public static void main(String[] args) throws Exception {
  6. File file = new File("D:\\data1.txt");
  7. FileInputStream fileStream = new FileInputStream(file);
  8. ObjectInputStream objStream = new ObjectInputStream(fileStream);

  9. Employee emp = (Employee) objStream.readObject();

  10. System.out.println(emp.toString());
  11. objStream.close();
  12. }
  13. }
Output: 
[id: 101, name: suresh, salary: 0.0]

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...