繁体   English   中英

Java可序列化的EOF

[英]Java Serializable EOF

已编辑,因此我尝试将.Product类型的对象保存在.ser文件中,其中包含以下名称:每次添加新产品时,我都会将其添加到文件中。 然后,每次启动窗口时,我想通过在窗口的构造函数中调用以下方法来读取以前保存在TreeSet中的这些产品:

public void updateCurrentProducts()
{
        Product p=null;
        System.out.println("Updating the tree of products.");
         try
          {
             FileInputStream fileIn = new FileInputStream("products.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             int c;
            // if((c=in.read()) != -1)
             {
                // System.out.println("Not eof yet.");
                 while ((p = (Product) in.readObject()) != null)
                 {
                     addProduct(p);
                     System.out.println("Just found "+p.name+".");
                 }
             }
             in.close();
             fileIn.close();
          }catch(IOException ix)
          {
             ix.printStackTrace();
             return;
          } catch (ClassNotFoundException e) 
         {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
    }

这是我添加产品的方式:

public void addProduct(Product p)
    {
        System.out.println("Succesfully added new peoduct.");

         FileOutputStream fileOut;
        try 
        {
            fileOut = new FileOutputStream("products.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(p);
            System.out.println("Just saved "+p.name);
            productTree.add(p);
             out.close();
             fileOut.close();
             System.out.printf("Serialized data is saved in products.ser");
        } 
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

但是我得到java.io.EOFException ,我不确定为什么,因为我有一个条件,除非((p = (Product) in.readObject()) != null)否则我不能访问/保存一个elem。 我不确定如何避免EOF。 我尝试使用read()检查,但是这样做只会避免问题,无法帮助我保存更改。 另外,我注意到仅保存了我提交的最后一个元素。 有什么建议么?

编辑实施建议后,我的错误切换到java.io.StreamCorruptedException: invalid type code: AC

我读到了这个https://stackoverflow.com/a/2395269/4180889,但是对于我来说,如果要保留内容我该怎么办还不清楚。

我注意到只有我提交的最后一个元素被保存。

这是因为写操作是在截断模式下完成的。

fileOut = new FileOutputStream("products.ser");

对附加模式使用true标志:

fileOut = new FileOutputStream("products.ser", true);

查看更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM