-2

I have a problem, I don't know how to read two objects from a single file in Java.

This is my code:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package prova.file;

/**
 *
 * @author Stefano
 */
import java.io.*;
import java.util.*;
public class ProvaFile implements Serializable {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws ClassNotFoundException {
        // TODO code application logic here
        objectone a=new objectone();
        objecttwo b=new objecttwo();
        objectone aa=null;
        objecttwo bb=null;
        Scanner m=new Scanner(System.in);
        System.out.println("inserisci per scegliere");
        int c=m.nextInt();
        switch (c){
     case 1: try{

              ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat"));
                oos.writeObject(a);
                oos.close();    

             }catch(Exception ex){
                System.out.println("Serialization Save Error : "+ex.getMessage());
            }
            break;
     case 2: try{
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat", true));
                oos.writeObject(b);
                oos.reset();
                oos.flush();
                oos.close();
             }catch(Exception ex){
                System.out.println("Serialization save error: "+ex.getMessage());
             }
             break;
    case 3:try{
        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("data.dat"));
        aa=(objectone)ois.readObject();
        bb=(objecttwo)ois.readObject();
        ois.close();
        }catch(IOException ex){
            System.out.println(ex.getMessage());
        }
        aa.getS();
        bb.getS();
        break;
    }
    }
}

I don't know if my fault is in the write or in the read, can you give me a little help?

Biffen
  • 5,354
  • 5
  • 27
  • 32
  • Are your objectone and objecttwo objects marked as serializable? Since those are the objects you are writing to a file they need to be serializable. – hendrikdelarey Apr 30 '15 at 12:03

3 Answers3

0

My suggestion is that you make a List of objects that you want to store. Now you have a single Object that you wish to store. So retrieving the the Object from the file will create the List object from which you can get back your original objects.

Blip
  • 2,711
  • 3
  • 17
  • 42
0

Inside Read

       ArrayList<WriteObject> woi=new ArrayList<>();
        woi=(ArrayList<WriteObject>)ois.readObject();

        for(int i=0;i<woi.size();i++){
            woi.get(i).getvalues();
        }

Inside Write

        ArrayList<WriteObject> woi=new ArrayList<>();       
        FileOutputStream fop=new FileOutputStream("c://object.ser");
        ObjectOutputStream oos=new ObjectOutputStream(fop);
        woi.add(wo);
        woi.add(wo1);
        oos.writeObject(woi);

WriteObject is the class that i used here to write objects wo and wo1 are objects added to the list and then written into file. Similarly I return the object as arraylist while reading and iterate the content. getvalue method is used locally to display object contents.

0

ciao, the problem is that ObjectOuputStream does not allow append as you can read here If you want to serialize multiple objects at the same time you must follow the "trick" explained in the link.

Here is you test case modified to make it work (I do not read from input, I make the calls one after the othe one).

package test;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Stefano
 */
import java.io.*;
import java.util.*;
public class ProvaFile implements Serializable {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws Exception {
        // TODO code application logic here
        objectone a=new objectone();
        objecttwo b=new objecttwo();
        objectone aa=null;
        objecttwo bb=null;



        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.dat"));
        oos.writeObject(a);
        oos.close(); 

        ObjectOutputStream oos2 = new AppendingObjectOutputStream(new FileOutputStream("data.dat", true));
        oos2.writeObject(b);
        //oos2.reset();
        //oos2.flush();
        oos2.close();

        ObjectInputStream ois=new ObjectInputStream(new FileInputStream("data.dat"));
        aa=(objectone)ois.readObject();
        bb=(objecttwo)ois.readObject();
        ois.close();
        aa.getS();
        bb.getS();        


    }

    public static class AppendingObjectOutputStream extends ObjectOutputStream {

          public AppendingObjectOutputStream(OutputStream out) throws IOException {
            super(out);
          }

          @Override
          protected void writeStreamHeader() throws IOException {
            // do not write a header, but reset:
            // this line added after another question
            // showed a problem with the original
            reset();
          }

        }    

    private static class objectone implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String s="uno";

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }

    }

    private static class objecttwo implements Serializable  {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String s="due";

        public String getS() {
            return s;
        }

        public void setS(String s) {
            this.s = s;
        }

    }    

}
Community
  • 1
  • 1
Giovanni
  • 3,561
  • 1
  • 19
  • 25