-1

I need a little bit of help in Java File IO operations. I am trying to append the serialized object to my file but only the last Object is being appended to the file. I have tried many suggestions but no success yet. How I can achieve this, please help?

Here is my Code:

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Scanner;




public class Working {

     String FILENAME = "E:\\assignment\\userpass\\userpass.txt";

    Scanner sc = new Scanner(System.in);
    String sUser = null, sPass = null, sRole = null;

    Signup signup = new Signup();

    public void createUser(){

        System.out.println(" Enter username: ");
        sUser = sc.next();

        System.out.println(" Enter password: ");
        sPass = sc.next();

        System.out.println(" Enter Role: ");
        sRole = sc.next();


        Working obj = new Working();

        signup.setUsername(sUser);
        signup.setPassword(sPass);
        signup.setRole(sRole);

        obj.serializeUser(signup);


    }





public void serializeUser(Signup signup){

        FileOutputStream fout = null;
        ObjectOutputStream oout= null;

        File file = new File(FILENAME);

        try{

        //  fout = new FileOutputStream(file);
        //  fout = new FileOutputStream(file.getAbsoluteFile(), true);
            fout = new FileOutputStream(file, true);
        //  fout = new FileOutputStream(FILENAME);
            oout = new ObjectOutputStream(fout);
            oout.writeObject(signup);

            System.out.println("User has been serialized");

        } catch(Exception e){
            e.printStackTrace();

        } finally {

            if(fout != null){
                try{

                    fout.close();
                } catch(IOException e){
                    e.printStackTrace();
                }
            } 

            if(oout != null){
                try{

                    oout.close();
                } catch(IOException e){
                    e.printStackTrace();
                }
            } 

        }

    }


// for test purpose
public void showUsers(){
    Working obj = new Working();
    Signup add = obj.deserializeUser(FILENAME);

    System.out.println(add);
}

// to show data
//test purpose

public Signup deserializeUser(String filename){

    Signup userDetails = null;
    File file = new File(FILENAME);

    FileInputStream fin = null;
    ObjectInputStream oin = null;

    try{

        fin = new FileInputStream(file);
        oin = new ObjectInputStream(fin);

        userDetails = (Signup) oin.readObject();

    } catch(Exception ex){
        ex.printStackTrace();
    } finally{
        if (fin != null) {
            try {
                fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (oin != null) {
            try {
                oin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return userDetails;

}

}

I have checked here already: 1. http://www.enseignement.polytechnique.fr/informatique/Java/1.8/java/io/FileOutputStream.html#FileOutputStream-java.lang.String-boolean- 2. Appending to an ObjectOutputStream

user207421
  • 305,947
  • 44
  • 307
  • 483
  • A quick glance at the ObjectOutputStream document doesn't lead me to believe there is an overload to writeObject that will append new objects. I think there's good reason for that. You may want to consider not serializing the object directly, but serialize it to string, and then write that to a file using the an outputstream with an append option. Deserialization would involve unmarshalling each line in your file to a new Signup object. Alternatively you could serialize a collection of your objects, and unmarshall the same collection type from it. – Mark W Aug 29 '17 at 19:07
  • @MarkW `String` is not a container for binary data. – user207421 Aug 29 '17 at 19:46
  • @EJP I was suggesting he serialize it to a string. There is no reason why he couldn't marshall his object to a string. The string can be anything from XML to comma delimited key value pairs for the fields. Doesn't really matter. Serialization is serialization, regardless of the storage format. – Mark W Aug 29 '17 at 19:59
  • @MarkW He is using Java Object Serialization. It produces a binary format. You can't serialize that to a `String`. If you're recommending he use a different serializer you needed to say so. – user207421 Aug 29 '17 at 20:06
  • @EJP, I misread that first time around.... nevertheless. I said serialize, not binary serialize with an object serializer. Serialization is not exclusively using this particular serialization method. My comment seems perfectly clear to me. – Mark W Aug 29 '17 at 20:12
  • @MarkW It isn't 'clear' in a question about Java Object Serialization, it's wrong. Without the information that you're talking about a different form of serialization (and incidentally one that doesn't use a binary format, not stated), the OP would be misled into trying it with his existing code and run into the problem that ... `String` isn't a container for binary data. This seems perfectly clear to me. – user207421 Aug 30 '17 at 00:47

1 Answers1

1

You need to create a new Signup object every time around the loop, or else call ObjectOutputStream.reset() each time, or use ObjectOutputStream.writeUnshared().

However there are other problems.

  • You should close the object output stream before the file output stream, or instead of.
  • You can't append to an object output stream, at least not as simply as this. See my answer about 'StreamCorruptedException - invalid type code AC' for why not. You need to use the technique in your second link.
user207421
  • 305,947
  • 44
  • 307
  • 483