反序列化对象只读取一个数据

时间:2015-06-05 04:14:12

标签: java object serialization file-io

如何从文件读取文件数据/反序列化对象。我创建了一个二进制文件文件,其中包含公司数据列表,我可以添加新公司及其相关数据,但当我想要读回所有文件数据它只提供第一个公司数据,它打印出来。下面的问题是我做了什么

 public class CompanyInfo extends Company { 
    int counter=0;
    Scanner in=new Scanner(System.in);
    private ArrayList<Company> companyinfo;

public CompanyInfo() {
    companyinfo=new ArrayList<Company>();
}

public void registercompany() {

    System.out.println("Enter Company Name \n");
    companyName=in.nextLine();
    System.out.println("\n");
    System.out.println("Enter Company Code \n");
    companyCode=in.nextLine();
    System.out.println("\n");
    System.out.println("Enter the Share Number \n");
    shareNo=in.nextInt();
    System.out.println("\n");
    System.out.println("Enter Closing Rate \n");
    closingRate=in.nextDouble();
    Company cin=new Company(companyName,companyCode,shareNo,closingRate);
    companyinfo.add(cin);

    try {
        ObjectOutputStream outObjFile =new ObjectOutputStream(new FileOutputStream("companies.dat",true));
        Company company = new Company(companyName,companyCode,shareNo,closingRate);
        outObjFile.writeObject(company);
        outObjFile.writeChars("\n");
        outObjFile.close();

    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("A file error has occurred. Sorry.");
        System.out.println( e.getMessage() );
    }


    counter++;  

    }
public void viewcompany(){
    try {
        ObjectInputStream inObjFile = new ObjectInputStream(
                new FileInputStream("companies.dat"));
                System.out.println(inObjFile.readObject()); // displays first object
                Company company = (Company)inObjFile.readObject(); // restores object
                System.out.println(company); // displays restored object
                inObjFile.close(); // finished with the file now.
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

2 个答案:

答案 0 :(得分:0)

我会做两种不同的方式。

  1. 将所有细节添加到hashmap并序列化该对象。所以在回读时,我可以使用&#34; key&#34;进行搜索。密钥可以是公司的名称或ID。您也可以使用ArrayList执行相同的操作。搜索可能很困难。 Immutable collections from Guava使用的内存更少,更好。
  2. 另一个解决方案是使用key.dat创建对象文件并将其放入名为company的目录中。这么容易回读和搜索。

答案 1 :(得分:0)

最后我找到了答案......希望它对其他人也有帮助......好运

public class CompanyInfo extends Company { 
    int counter=0;
    private static String filename = "company.dat";
    Scanner in=new Scanner(System.in);
    private ArrayList<Company> companyinfo;

    public CompanyInfo() {
        companyinfo=new ArrayList<Company>();
    }

public void registercompany() {


    System.out.println("Enter Company Name \n");
    companyName=in.nextLine();
    System.out.println("Enter Company Code \n");
    companyCode=in.nextLine();
    System.out.println("Enter the Share Number \n");
    shareNo=in.nextInt();
    System.out.println("Enter Closing Rate");
    closingRate=in.nextDouble();
    Company cin=new Company(companyName,companyCode,shareNo,closingRate);
    companyinfo.add(cin);
File file=new File(filename);
boolean append=true;
ObjectOutputStream out=null;
try {
    if (!file.exists()||!append) {
        out=new ObjectOutputStream(new FileOutputStream(filename));
    }
    else
    {
        out=new AppendableObjectOutputStream(new FileOutputStream (filename, append));
    }
    Company company = new Company(companyName,companyCode,shareNo,closingRate);
    out.writeObject(company);
    out.flush();

} catch (Exception e){
    e.printStackTrace ();
}finally{
    try{
        if (out != null) out.close ();
    }catch (Exception e){
        e.printStackTrace ();
    }
}

    counter++;  

    }
public void viewcompany(){
    try {
        List<Object> results = new ArrayList<Object>();
        FileInputStream fis = new FileInputStream(filename);
        ObjectInputStream ois = new ObjectInputStream(fis);
        try{
        while (true) {
        results.add(ois.readObject());}
            }
        catch (OptionalDataException e) {
            if (!e.eof) throw e; } 
        finally {
            System.out.println(results);
            //System.out.println(((Company)results.get(0)).companyName);
            ois.close(); }
    }
    catch (Exception e){
        System.out.println(e.getMessage());
    }

}
private static class AppendableObjectOutputStream extends ObjectOutputStream {
    public AppendableObjectOutputStream(OutputStream out) throws IOException {
      super(out);
    }

    @Override
    protected void writeStreamHeader() throws IOException {}
  }
}