Using ObjectInputStream:
Output:
[id: 101, name: suresh, salary: 2000.0]
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.ObjectInputStream;
- public class ReadFileByObjectInputStreamExe {
- public static void main(String[] args) throws Exception {
- File file = new File("D:\\data1.txt");
- FileInputStream fileStream = new FileInputStream(file);
- ObjectInputStream objStream = new ObjectInputStream(fileStream);
- Employee emp = (Employee) objStream.readObject();
- System.out.println(emp.toString());
- objStream.close();
- }
- }
Employee.java:
- 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 + "]";
- }
- }
[id: 101, name: suresh, salary: 2000.0]
No comments:
Post a Comment