Sunday, April 29, 2018

Read file using ObjectInputStream !!

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. }
Employee.java:
  1. import java.io.Serializable;
  2. class Employee implements Serializable {

  3. private static final long serialVersionUID = 1L;
  4. int id;
  5. String name;
  6. double salary;
  7. // transient double salary;

  8. public Employee(int id, String name, double salary) {
  9. this.id = id;
  10. this.name = name;
  11. this.salary = salary;
  12. }

  13. @Override
  14. public String toString() {
  15. return "[id: " + id + ", name: " + name + ", salary: " + salary + "]";
  16. }
  17. }
Output: 
[id: 101, name: suresh, salary: 2000.0]

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...