Using ObjectOutputStream class & transient keyword:
ͭ sr com.ishaan.filehandling.Employee I idL namet Ljava/lang/String;xp et suresh
Read transient field data from a file using ObjectInputStream:
[id: 101, name: suresh, salary: 0.0]
- 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();
- }
- }
ͭ sr com.ishaan.filehandling.Employee I idL namet Ljava/lang/String;xp et suresh
Read transient field data from a file using ObjectInputStream:
- 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();
- }
- }
[id: 101, name: suresh, salary: 0.0]
No comments:
Post a Comment