将对象从文件读取到ArrayList

时间:2011-02-13 03:50:01

标签: java

当我试图读取一个对象并存储在arraylist中但我得到一个例外时,这是我面临问题的代码部分。

public class Customer implements Serializable  {

private String username;
private String password;
private int age;
private String accttype;
private String acctno;
private float amount;

Customer() {
    System.out.println("Im in Customer");
}

public boolean writeToDataBase(String uname, String pwd, int cage, String caccttype, String cacctno, float camount) throws IOException  {

    Customer custobj = new Customer();
    FileOutputStream fos=null;
    ObjectOutputStream oos=null;
    custobj.username = uname;
    custobj.password = pwd;
    custobj.age = cage;
    custobj.accttype = caccttype;
    custobj.acctno = cacctno;
    custobj.amount = camount;
    try {

        fos=new FileOutputStream("Customerdetails.txt",true);
        oos=new ObjectOutputStream(fos);
        oos.writeObject(custobj);
        oos.close();
        fos.close();
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
        return false;
    }
    finally
    {
        fos.close();
        oos.close();
    }
}

public boolean retriveFromDataBase(int a) throws IOException
{
    try {
        Customer custobj = new Customer();
        FileInputStream fis=null;
        ObjectInputStream ois=null;
        ArrayList<Customer> custlist;
        try {
             custlist = new ArrayList<Customer>();
            fis = new FileInputStream("Customerdetails.txt");
            ois = new ObjectInputStream(fis);
            while (fis.available()!=0) {
                custobj=(Customer)ois.readObject();
                custlist.add(custobj);
            }
            System.out.println("Customer List" + custlist.size());
            if (a == 3) {
                for (int i = 0; i < custlist.size(); i++) {
                    custobj = custlist.get(i);
                    custobj.displayCustomers();
                }
            }
            return true;

        } catch (Exception ex) {
            System.out.println(ex.toString());
            System.out.println("No users are presnt in the file");
            return false;
        }
        finally
        {
            ois.close();
            fis.close();
        }
    }
    catch(Exception ex)
    {
        System.out.println(ex.toString());
        return false;
    }
}
public void displayCustomers()
{
    try
    {
        System.out.println("details"+username+"\t"+age+"\t"+password+"\t"+acctno+"\t"+accttype+"\t"+amount);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
}
}

2 个答案:

答案 0 :(得分:0)

您的对象是否实现了Serializiable或Externalizeable接口?如果是,您是否使用不实现可序列化/外部化的非传递对象,并且不提供无参数的默认构造函数?

没有进一步的信息(哪个例外,更多的代码),很难说。

答案 1 :(得分:0)

我注意到,当你第二次运行它时,程序会抛出java.io.StreamCorruptedException。只运行一次它就能正常工作。

问题是,每次在writeToDatabase(..)方法中序列化时,都无法APPEND到同一个文件:Customerdetails.txt。因此,在writeToDatabase(..)方法中调用FileOutputStream的构造函数时,删除append标志:“true”。