Thursday 13 March 2014

How to Serializated multple Object in Java


Few days before as per requirement, need to build a class that serialized an object and store in a file and later should be retrieved through de-serialized process.

As per requirement, every Save Button clicked bean object should be serialized in a file and on Load Button click all persisted object could be back to JListBox.When i started this stuff then serialization are working file and store on the files But when Click on a Load Button then throws an exception.
then i did google on web after spending some time,i screw it in some other ways myself which is given below,this is fit for our requirement and working  good.

java.io.StreamCorruptedException: invalid type code: AC


HostPersistor.Java class is responsible to take a HostInfo bean and serialized and de-serialized.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.bean.HostInfo;

public class HostPersistor {

    static Map<String,HostInfo> HostInfoMap = new Hashtable<String,HostInfo>();
    public static void write(HostInfo obj) {

        FileOutputStream fout = null;
        ObjectOutputStream objout = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            if (!file.exists()) {
                file.createNewFile();
            }
            fout = new FileOutputStream(file);

            if (!HostInfoMap.containsKey(obj)) {
                HostInfoMap.put(obj.getIpaddress(),obj);
                objout = new ObjectOutputStream(fout);
                for (Map.Entry<String,HostInfo> info : HostInfoMap.entrySet()) {
                    objout.writeObject(info.getValue());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (objout != null)
                    objout.close();
                if (fout != null)
                    fout.close();

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

        }

    }

   
    private static Set<String> readObject() {

        FileInputStream fin = null;
        ObjectInputStream objin = null;
        try {
            File file = new File("HOST_SESSION_HISTORY.ser");
            objin = new ObjectInputStream(new FileInputStream(file));
            while (true) {
                try {
                    HostInfo info = (HostInfo) objin.readObject();
                    HostInfoMap.put(info.getIpaddress(),info);
                } catch (Exception e) {
                    break;
                }

            }
        } catch (IOException e) {

        } finally {
            try {
                if (objin != null)
                    objin.close();
                if (fin != null)
                    fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       
        return HostInfoMap.keySet();
    }

    public static Set<String> getHostInfos() {
        return readObject();
    }

    public static List<String> getHosts(){
       
        List<String> list = new ArrayList<String>();
        list.addAll(getHostInfos());
        Collections.sort(list);
        return list;
       
    }
   

    public static void main(String args[]) throws IOException {

       
        HostInfo info1 = new HostInfo("xxxx", "xx", "xxx", 22);
        HostInfo info2 = new HostInfo("aaaa", "aaaa", "aaa", 22);
        HostInfo info3 = new HostInfo("yyyyy", "yyy", "yyyy", 22);
       
        write(info1);
        write(info2);
        write(info3);
       
        for(String info : getHostInfos()){
           
            System.out.println(info);
           
        }
       
       
        //System.out.println(getHosts());
    }


    public static Map<String, HostInfo> getHostInfoMap() {
        return HostInfoMap;
    }


    public static void setHostInfoMap(Map<String, HostInfo> hostInfoMap) {
        HostInfoMap = hostInfoMap;
    }

}

HostInfo.Java bean which describe host information.

import java.io.Serializable;
import java.util.Stack;

/**
 * @author ajaykumar.gupta
 *
 */

public final class HostInfo implements Serializable,Comparable<HostInfo> {

    private static final long serialVersionUID = 6243919138889562890L;

    private String ipaddress;
    private String username;
    private String password;
    private String pwd;
    private Stack<String> cmdList = new Stack<String>();

    private int port;
   

    public HostInfo(String ipaddress, String username, String password, int port) {

        this.ipaddress = ipaddress;
        this.username = username;
        this.password = password;
        this.port = port;
       
        cmdList.add(this.username+"@"+this.ipaddress);

    }

    public String getIpaddress() {
        return ipaddress;
    }

    public void setIpaddress(String ipaddress) {
        this.ipaddress = ipaddress;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Stack<String> getCmdList() {
        return cmdList;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("HostInfo [ipaddress=");
        builder.append(ipaddress);
        builder.append(", username=");
        builder.append(username);
        builder.append(", password=");
        builder.append(password);
        builder.append(", port=");
        builder.append(port);
        builder.append(", pwd=");
        builder.append(pwd);
        builder.append(", cmdList=");
        builder.append(cmdList);
        builder.append("]");
        return builder.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((ipaddress == null) ? 0 : ipaddress.hashCode());
        result = prime * result + port;
        result = prime * result
                + ((username == null) ? 0 : username.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        HostInfo other = (HostInfo) obj;
        if (ipaddress == null) {
            if (other.ipaddress != null)
                return false;
        } else if (!ipaddress.equals(other.ipaddress))
            return false;
        if (port != other.port)
            return false;
        if (username == null) {
            if (other.username != null)
                return false;
        } else if (!username.equals(other.username))
            return false;
        return true;
    }

    @Override
    public int compareTo(HostInfo o) {
        return this.ipaddress.compareTo(o.ipaddress);
    }
   
   
   

}