Knowledge Walls
John Peter
Pune, Maharashtra, India
How to read and write object in file in java?
1661 Views
ObjectStreamReadAndWrite
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class Students implements Serializable{
    private int rno;
    private String studentName;
    
    public int getRno() {
        return rno;
    }
    public void setRno(int rno) {
        this.rno = rno;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    
    public String toString(){
        return "["+rno+","+studentName+"]";
    }
}
public class ObjectStreamReadAndWrite {
    public static void main(String args[]) throws Exception {
        List<Students> studentList = new ArrayList<Students>();
        {
            Students student = new Students();
                student.setRno(1001);
                student.setStudentName("John");
            studentList.add(student);
        }
        {
            Students student = new Students();
                student.setRno(1002);
                student.setStudentName("Raja");
            studentList.add(student);
        }
        {
            Students student = new Students();
                student.setRno(1003);
                student.setStudentName("Jasmin");
            studentList.add(student);
        }
        
        
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("studentObjectData.src"));
            oos.writeObject(studentList);
        
            oos.flush();
            oos.close();
            
        List<Students> fetchedStudentList = new ArrayList<Students>();
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("studentObjectData.src"));
            fetchedStudentList = (List<Students>) ois.readObject();
            
        System.out.println(fetchedStudentList);
        ois.close();
    }
}
StudentObjectData.src 
Output 
Best Lessons of "One day One Thing to Know"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details