简体   繁体   中英

Writing multiple objects of different classes in the same file

Is it possible to write multiple objects of different classes in the same file using serialization if so how will i be able read different objects from the same file

FileOutputStream file=new FileOutputStream("G:\\File.txt");
        FileInputStream fileread=new FileInputStream("G:\\File.txt");
        ObjectOutputStream write=new ObjectOutputStream(file);
        ObjectInputStream read=new ObjectInputStream(fileread);
        
        Teacher tc=new Teacher();
       Teacher tc2=new Teacher();
        tc.name="Ahmad";
        tc.age=21;
        tc2.name="Bilal";
        tc2.age=19;
        Student std=new Student();
        std.name="Ahmad";
        std.age=21;
        try{
            
        
        write.writeObject(tc);
                write.writeObject(tc2);
                write.writeObject(std);
        }
        catch(Exception e){
          
        } 
Teacher tc3=(Teacher)read.readObject();
           Student std4=(Student)read.readObject(); 

This is what i have been trying to do

Is it possible to write multiple objects of different classes in the same file using serialization

Yes it is possible.

... if so how will i be able read different objects from the same file

You read them using readObject in the same order that you wrote them with writeObject .


It looks like the problem with your attempt is that that you write two Teacher objects followed by a Student object... but you read one Teacher objects followed by a Student object. So you will get a class cast exception because you are attempting to task a Student to a Teacher .

Another possible flaw in your code is that you may not be writing the object stream header soon enough.

The problem is that when you construct an ObjectInputStream it will eagerly attempt to read the object stream header from the stream that you wrapped. The ObjectOutputStream constructor will write the head, but until something flushes (or closes) the ObjectOutputStream , the header may not be written its wrapped output stream. If the attempt to read the header happens before it is actually written, the ObjectInputStream constructor will thrown an exception saying that the object stream is corrupt.

Indeed, you always have to be careful about this kind of thing when you application is simultaneously trying to read and write the same file. My advice would be to avoid doing that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM